繼初始化成員是在C初始化結構成員錯誤在一個結構
struct stack
{
int *a;
int top;
int size;
}s;
void init()
{
const int size =10; /*s.size=10;*/ /*const int s.size=10*/
s.a=(int*)malloc(size*sizeof(int));
s.top=0;
}
int main()
{
init();
printf("Initialization done !\n");
return 0;
}
Q1一個程序:在init
方法,而不是const int size=10
當我寫s.size=10
,我得到一個錯誤「大小未在範圍中聲明」,但我已經在stack
結構中聲明size
結構。我能夠以相同的方式初始化top
那麼爲什麼錯誤?
Q2:在init
方法,我得到正確的輸出與const int size=10
。我很困惑,在這個聲明中,我們如何能夠在不使用結構變量的情況下訪問size
struct stack
的成員,不應該是const int s.size=10
?
請[不要投]](http://stackoverflow.com/q/605845/2173917)'malloc()'的返回值。 –
編譯器抱怨不是關於's.size = 10',而是關於sa =(int *)的'size' malloc(size * sizeof(int));'當你移除const int size = 10' –