2014-04-01 77 views
0

下面的代碼工作(沒有錯誤),但我得到了奇怪的輸出,因爲這從下面的代碼:下面代碼給出了奇怪的輸出

OUTPUT:

名稱是8îk和數量是0

名稱是數量和數量是2130567168

我的錯誤在哪裏?

#include <stdio.h> 
#include <stdlib.h> 

void display(struct item *); 

struct item{ 

char name[50]; 
int quantity; 

}; 

int main(void){ 

struct item *first = (struct item *)malloc(sizeof(struct item)); 
strcpy(first->name, "Banana"); 
first->quantity = 32; 

struct item *second = (struct item *)malloc(sizeof(struct item)); 
strcpy(second->name, "Apple"); 
second->quantity = 432; 

display(&first); 
display(&second); 

getch(); 

} 

void display(struct item *i){ 

printf("Name is %10s and quantity is %7d\n", i->name, i->quantity); 

} 

回答

3

firstseconds已經指針,所以你並不需要通過他們的地址,但它們的價值(他們指向的結構的地址):

display(first); 
display(second); 
+0

非常感謝答案 – Lyrk

1
display(first); 
display(second); 

firstsecond已經是指針了,按display結構要求。

1

除了致電display()時出現的明顯錯誤,您還錯過了#include <string.h>。如果你有compiled with warnings enabled你就已經警覺到這一點,並與呼叫的問題display()等幾個問題太:

Line 4: warning: 'struct item' declared inside parameter list 
Line 4: warning: its scope is only this definition or declaration, which is probably not what you want 
In function 'main': 
Line 16: warning: incompatible implicit declaration of built-in function 'strcpy' 
Line 23: warning: passing argument 1 of 'display' from incompatible pointer type 
Line 24: warning: passing argument 1 of 'display' from incompatible pointer type 
t.c: At top level: 
Line 30: error: conflicting types for 'display' 
Line 4: error: previous declaration of 'display' was here 

這個故事的寓意是:總是啓用警告編譯,並採取注意任何警告!

還有一點需要注意:您應該never cast the result of malloc in C,例如never cast the result of malloc in C

struct item *first = malloc(sizeof(struct item)); // do not apply redundant and 
                // potentially dangerous cast! 
+0

謝謝我會打開警告。 – Lyrk

1

你傳遞指針的地址到結構到功能的「顯示屏」,而不是傳遞的結構本身的地址。 (你正在傳遞「struct item **」)。

display(first); display(second);將解決問題。