2014-12-20 72 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