[英]Initializing array of structs in c
将初始化更改为:
record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };
/* ^ ^ ^ ^ ^ ^ */
使用(...)
初始化会产生类似于{"one", "two", "three"}
并创建一个结构数组,其元素为{ {(int)"one", "two"}, {(int)"three", (char *)0} }
C中的逗号运算符从左到右计算表达式并丢弃除最后一个之外的所有表达式。 这就是为什么原因1
, 2
和3
被丢弃。
您没有正确初始化list
。 在把初始化元素()
将让编译器把,
如逗号操作符 ,而不是分离 。
您的编译器应该提供这些警告
[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] missing braces around initializer [-Wmissing-braces]
[Warning] (near initialization for 'list[0]') [-Wmissing-braces]
[Warning] initialization makes integer from pointer without a cast [enabled by default]
[Warning] (near initialization for 'list[0].value') [enabled by default]
[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] left-hand operand of comma expression has no effect [-Wunused-value]
[Warning] initialization makes integer from pointer without a cast [enabled by default]
[Warning] (near initialization for 'list[1].value') [enabled by default]
[Warning] missing initializer for field 'name' of 'record' [-Wmissing-field-initializers]
初始化应该作为
record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.