在C中通过引用传递struct

时间:2010-11-30 16:57:23

标签: c struct

这段代码是否正确?它按预期运行,但这个代码是否正确使用结构的指针和点表示法?

struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}

5 个答案:

答案 0 :(得分:48)

你使用指针和点符号是好的。如果出现问题,编译器应该给你错误和/或警告。

以下是代码的副本,其中包含一些额外的注释和事项,可以考虑使用结构和指针以及函数和变量范围。

// Define the new variable type which is a struct.
// This definition must be visible to any function that is accessing the
// members of a variable of this type.
struct someStruct {
    unsigned int total;
};

/*
 * Modifies the struct that exists in the calling function.
 *   Function test() takes a pointer to a struct someStruct variable
 *   so that any modifications to the variable made in the function test()
 *   will be to the variable pointed to.
 *   A pointer contains the address of a variable and is not the variable iteself.
 *   This allows the function test() to modify the variable provided by the
 *   caller of test() rather than a local copy.
 */
int test(struct someStruct *state) {
    state->total = 4;
    return 0;
}

/* 
 * Modifies the local copy of the struct, the original
 * in the calling function is not modified.
 * The C compiler will make a copy of the variable provided by the
 * caller of function test2() and so any changes that test2() makes
 * to the argument will be discarded since test2() is working with a
 * copy of the caller's variable and not the actual variable.
 */
int test2(struct someStruct state) {
    state.total = 8;
    return 0;
}

int test3(struct someStruct *state) {
    struct someStruct  stateCopy;
    stateCopy = *state;    // make a local copy of the struct
    stateCopy.total = 12;  // modify the local copy of the struct
    *state = stateCopy;    /* assign the local copy back to the original in the
                              calling function. Assigning by dereferencing pointer. */
    return 0;
}

int main () {
    struct someStruct s;

    /* Set the value then call a function that will change the value. */
    s.total = 5;
    test(&s);
    printf("after test(): s.total = %d\n", s.total);

    /*
     * Set the value then call a function that will change its local copy 
     * but not this one.
     */
    s.total = 5;
    test2(s);
    printf("after test2(): s.total = %d\n", s.total);

    /* 
     * Call a function that will make a copy, change the copy,
       then put the copy into this one.
     */
    test3(&s);
    printf("after test3(): s.total = %d\n", s.total);

    return 0;
}

答案 1 :(得分:15)

这是结构的正确用法。您的退货值存在疑问。

另外,因为您正在打印unsigned int,所以应该使用%u而不是%d

答案 2 :(得分:3)

是的,没错。它生成一个结构s,将其总数设置为5,将指向它的指针传递给一个函数,该函数使用指针将总数设置为4,然后将其打印出来。 ->用于指向结构的指针成员,.用于结构成员。就像你使用它们一样。

但返回值不同。 test可能无效,main最后需要return 0

答案 3 :(得分:1)

是的。这是正确的。如果不是(从./ - >视角),你的编译器就会大叫。

答案 4 :(得分:0)

是的,它正确使用结构。您也可以使用

struct someStruct s;

然后您不必一次又一次地写someStruct s;,但可以使用evaluate()