您需要像初始化第二个 struct 的对象一样,将整型字符常量括在大括号中
struct s{
char a;
}s1 = { 'A' };
来自C标准(6.7.9初始化)
否则,具有Aggregate或
联合类型应该是用大括号括起来的初始值设定项列表
元素或命名成员.
使用字符串文字作为可以不带大括号的字符数组的初始值设定项是不允许的.
例如,这些声明是等价的
char s[] = { "Hello" };
和
char s[] = "Hello";
然而,第二个方案也是不正确的.
您声明了一个 struct 类型的对象数组
struct s{
char *q;
}s1[]= {"A"};
该声明相当于
struct s{
char *q;
}s1[1]= {"A"};
Such an initialization is valid due to the C St和ard (6.7.9 Initialization)
20 If the aggregate or union contains elements or members that are
aggregates or unions, these rules apply recursively to the
subaggregates or contained unions. If the initializer of a
subaggregate or contained union begins with a left brace, the
initializers enclosed by that brace 和 its matching right brace
initialize the elements or members of the subaggregate or the
contained union. Otherwise, only enough initializers from the list
are taken to account for the elements or members of the subaggregate
or the first member of the contained union; any remaining initializers
are left to initialize the next element or member of the aggregate of
which the current subaggregate or contained union is a part.
表达式&s1
具有类型struct s( * )[1]
,但它被赋给类型struct s *
的指针
struct s *ptr = &s1;
这些指针类型之间不存在隐式转换.
编译器应该发出警告.您不应忽略编译器警告.
该代码之所以有效,是因为 struct 类型的对象的地址等于其第一个数据成员的地址.