要求如下:建立一个结构体(A),该结构体成员包括一个字符数组和另一个结构体(B)。这个内嵌的结构体又包含三个成员,均为字符串数组。然后创建A结构体的数组,包含5个元素。完成这一步之后对该数组进行初始化。内容为:让结构体A中的字符串装载一串数字字符。让结构体B中的三个成员分别装载一个英文名字。还要求将数组A的第五个元素中的结构体B中的第二字符数组不加以初始化,即不去对其做任何处理。
#include
#define NUM 8
#define MAX 81
#define SIZE 5
typedef struct names{
char first[MAX];
char middle[MAX];
char surname[MAX];
}NAME;
typedef struct data{
char socialnumber[NUM];
NAME namedata;
}DAT;
DAT infodat[SIZE] = {
{"12345678",{"Michael","Simon","May"}},
{"12345687",{"Jackel","Mason","Joe"}},
{"12345768",{"Sharon","Jason","Lee"}},
{"12345786",{"Paul","Murray","Peterson"}},
[4] = {"12345876", {"Gollan", .surname = "Jule"} } //这个元素中的结构体B的第二个字符串不用初始化
}; //所以我直接指定初始化第三个字符串,跳过第二个
//结果出错说 'namedata' not declared here (not in a function)
int main(void){
;
}
ISO C99的标准文档里的例子说的很清楚了嘛.
6.7.8 Initialization
Syntax
1 initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }
initializer-list:
designationopt initializer
initializer-list , designationopt initializer
designation:
designator-list =
designator-list:
designator
designator-list designator
designator:
[ constant-expression ]
. identifier
========
说实话, 这个俺也没有理解透彻, 因为俺是半路出家的.
没有系统地学过编译原理, 对这些文法也是一知半解.
不过洋鬼子的书就是好, 后面的例子几乎涉及了所有的
初始化方法.
比如楼主遇到的问题: 看看书上的这几个例子就应该能明白了.
33 EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using
designators:
enum { member_one, member_two };
const char *nm[] = {
[member_two] = "member two",
[member_one] = "member one",
};
34 EXAMPLE 10 Structure members can be initialized to nonzero values without depending on their order:
div_t answer = { .quot = 2, .rem = -1 };
35 EXAMPLE 11 Designators can be used to provide explicit initialization when unadorned initializer lists
might be misunderstood:
struct { int a[3], b; } w[] =
{ [0].a = {1}, [1].a[0] = 2 };
阅读(2950) | 评论(0) | 转发(0) |