繁体   English   中英

在c中初始化结构数组

[英]Initializing array of structs in c

我初始化了一个包含三个项目的结构数组, 为我显示了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[] = { {1, "one"}, {2, "two"}, {3, "three"} };
/*                ^        ^  ^        ^  ^          ^  */

使用(...)初始化会产生类似于{"one", "two", "three"}并创建一个结构数组,其元素为{ {(int)"one", "two"}, {(int)"three", (char *)0} }

C中的逗号运算符从左到右计算表达式并丢弃除最后一个之外的所有表达式。 这就是为什么原因123被丢弃。

您没有正确初始化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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM