【问题标题】:Initializing array of structs in c在c中初始化结构数组
【发布时间】:2015-04-29 16:20:33
【问题描述】:

我已经用三个项目和it is showing 2 为我初始化了一个结构数组!!!

#include <stdio.h>

typedef struct record {
    int value;
    char *name;
} record;

int main (void) {
    record list[] = { (1, "one"), (2, "two"), (3, "three") };
    int n = sizeof(list) / sizeof(record);

    printf("list's length: %i \n", n);
    return 0;
}

这里发生了什么?我疯了吗?

【问题讨论】:

  • 是否有任何错误或只是静默失败?
  • 您甚至应该无法运行该代码。它会给你错误,因为你没有正确初始化record list[]

标签: c arrays struct


【解决方案1】:

将初始化更改为:

record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };
/*                ^        ^  ^        ^  ^          ^  */

您使用(...) 进行的初始化会产生类似于{"one", "two", "three"} 的效果并创建一个带有元素{ {(int)"one", "two"}, {(int)"three", (char *)0} } 的结构数组

comma operator 在 C 中从左到右计算表达式并丢弃除最后一个之外的所有表达式。这就是123被丢弃的原因。

【讨论】:

  • 你能解释一下为什么sizeof(list)在初始化错误的时候返回16?
  • 谢谢.. 现在我看到了问题
  • 如果答案有帮助我很高兴:)
【解决方案2】:

您没有正确初始化list将初始化元素放入() 将使编译器将, 视为comma operator 而不是分隔符

你的编译器应该给出这些警告

[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"} };  

【讨论】:

  • 谢谢...我没有看到这个警告... ideone将它编译为普通代码
猜你喜欢
  • 2010-09-23
  • 2010-12-06
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
相关资源
最近更新 更多