2010-11-30 80 views
24

此代碼是否正確?它按預期運行,但是這個代碼是否正確地使用了結構的指針和點符號?以C中的引用形式傳遞結構

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); 
} 
+1

爲什麼測試應該返回一個int?實際上並沒有回到那裏。 – Muggen 2010-11-30 16:59:45

+0

C有參考嗎?驚訝...... – 2010-11-30 17:01:44

回答

15

這是結構的正確用法。有關於你的回報值的問題。

此外,因爲您正在打印一個unsigned int,所以應該使用%u而不是%d

1

是的。這是正確的。如果它不是(從。/ - >觀點),你的編譯器會大聲叫嚷。

3

是的,沒錯。它會創建一個結構s,將其總數設置爲5,將指針傳遞給使用該指針的函數將總數設置爲4,然後將其打印出來。 ->適用於結構指針的成員,.適用於結構成員。就像你用它們一樣。

雖然返回值不同。 test應該可能是無效的,並且main在其末尾需要return 0

39

您使用指針和點符號是很好的。如果出現問題,編譯器應該給你錯誤和/或警告。

下面是您的代碼的副本,其中還有一些附加說明以及有關使用結構和指針以及函數和變量範圍的內容。

// 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; 
}