2014-12-20 36 views
1

繼初始化成員是在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

+0

請[不要投]](http://stackoverflow.com/q/605845/2173917)'malloc()'的返回值。 –

+1

編譯器抱怨不是關於's.size = 10',而是關於sa =(int *)的'size' malloc(size * sizeof(int));'當你移除const int size = 10' –

回答

0

我想,你的困惑是因爲你使用了相同的變量名size兩次,

  1. 作爲結構成員變量
  2. void init()一個局部變量。

請注意,這兩個是單獨的變量。

size成員變量struct stack是該結構的成員。您需要通過.->運算符訪問成員變量[是,即使結構是全局的]。

OTOH,int size in void init()是類型爲int的正常變量。

沒有struct stack類型的變量,不存在size,它屬於struct stack。同樣,您無法在任何地方直接訪問size,這是struct stack中的成員變量[不使用類型爲struct stack的結構變量]。

總結

答1:

的錯誤不是與s.size = 10更換const int size=10。這是相當的下一行,

s.a= malloc(size*sizeof(int)); 
      ^
       | 

在哪裏,size變量存在時const int size=10被刪除。

回答2

const int size=10聲明並定義了一個名爲size新變量。這與s.size [struct stack的成員]不一樣。這就是爲什麼使用

s.a= malloc(size*sizeof(int)); 
      ^
       | 

是有效的,因爲名爲size的變量在範圍內。

2

是的size是一個結構變量,你必須訪問結構變量並初始化它。

如果初始化爲size =10它將作爲新變量。因爲init函數將存儲在單獨的堆棧中,變量size的作用域將僅在init函數內部。 然後,在分配內存時,應該爲s.size變量分配內存。

s.a = malloc(s.size * sizeof(int)); 
2

s.size=10沒有問題。問題是,當你s.a分配內存,有沒有名爲size變量,您應將其更改爲:

s.a = malloc(s.size * sizeof(int)); 

你似乎混淆了在結構struct stack s變量size和成員size,他們不除了具有相同的名稱之外。

0
Note: the following method of defining/declaring a struct is depreciated 
struct stack 
{ 
    int *a; 
    int top; 
    int size; 
}s; 

The preferred method is: 
// declare a struct type, named stack 
struct stack 
{ 
    int *a; 
    int top; 
    int size; 
}; 

struct stack s; // declare an instance of the 'struct stack' type 

// certain parameters to the compile command can force 
// the requirement that all functions (other than main) 
// have a prototype so: 
void init (void); 

void init() 
{ 

    s.size =10; 
    // get memory allocation for 10 integers 
    if(NULL == (s.a=(int*)malloc(s.size*sizeof(int)))) 
    { // then, malloc failed 
     perror("malloc failed"); 
     exit(EXIT_FAILURE); 
    } 

    s.top=0;  
} // end function: init