2014-11-02 158 views
0

遇到的错误是:'{'标记之前的预期表达式。为什么是这样?结构数组初始化

#include <stdio.h> 
int main() 
{ 
    struct test 
    { 
     char a[100]; 
     int g; 
    } b[2]; 
    b[0] = {"Maharshi", 5}; 
    b[1] = {"Hello", 6}; 
    printf("%u %u", &b[0], &b[1]); 
    return 0; 
} 

回答

4

您可能不会将初始化程序列表分配给已定义的对象。

b[0] = {"Maharshi", 5}; 
b[1] = {"Hello", 6}; 

但是你可以做你想做的复合文字的意思:

b[0] = (struct test){ "Maharshi", 5 }; 
b[1] = (struct test){ "Hello", 6 }; 

或者使用初始化列表被定义数组的时候。

1

当声明结构时,不能使用列表初始化! 您也可以使用这样的:

int main() { 
    struct test{ 
      char a[100]; 
      int g; 
    }b[2] = 
    {{"Maharshi", 5}, 
    {"Hello", 6}}; 

    printf("%u %u", b[0].g, b[1].g); 

    return 0; 
} 

(需要注意的是里面括号optionnal)