在C语言中初始化结构体数组

5

我已经用三个项目初始化了一个结构体数组,但是显示为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;
}

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


有错误吗,还是没有任何提示的失败了? - JabberwockyDecompiler
你甚至不应该能够运行那段代码。因为你没有正确初始化record list[],所以它会给你报错。 - Javia1492
2个回答

4

将初始化更改为:

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

您使用 (...) 进行初始化后,效果类似于 {"one", "two", "three"} 并创建了一个包含元素为 { {(int)"one", "two"}, {(int)"three", (char *)0} } 的结构体数组。
在 C 语言中,逗号运算符 从左到右计算表达式,并且弃掉除最后一个之外的所有内容。这就是为什么数字 123 被舍弃的原因。

你能解释一下为什么错误初始化时 sizeof(list) 返回 16 吗? - user2018675
谢谢,现在我看到问题了。 - user4227915
如果答案有帮助到您,我很高兴 :) - Mohit Jain

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

谢谢...我没有看到这些警告...ideone将其编译为正常代码。 - user4227915

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接