2011-02-28 29 views
0
#include<stdio.h> 
#include<stdlib.h> 
struct test 
{ 
    int x; 
    int *y; 
}; 

main() 
{ 
    struct test *a; 
    a = malloc(sizeof(struct test)); 

    a->x =10; 
    a->y = 12; 
    printf("%d %d", a->x,a->y); 
} 

我得到的O/P,但有一個警告輸入數據以構造部件是指針

warning: assignment makes pointer from integer without a cast 

warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’ 

如何輸入一個值到* Y結構測試

+1

道格的答案是100%正確的。不過,我認爲你真正需要的是閱讀指針,我不認爲特別解決這個情況會對你有所幫助。有很好的教程,你可以谷歌。 – slezica

回答

6

要訪問,您需要解除引用由表達式返回的指針a-> y操縱指向的價值。要做到這一點,使用一元*運算符:

您還需要分配內存爲y以確保它指向的東西:

a->y = malloc(sizeof(int)); 
... 
*(a->y) = 12; 
... 
printf("%d %d", a->x,*(a->y)); 

而且一定以相反的順序來釋放malloc分配數據它是malloc'd

free(a->y); 
free(a);