在 c 中初始化结构数组

5 c arrays struct

我已经用三个项目初始化了一个结构数组,为我显示了 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Moh*_*ain 4

将初始化更改为:

record list[] = { {1, "one"}, {2, "two"}, {3, "three"} };
/*                ^        ^  ^        ^  ^          ^  */
Run Code Online (Sandbox Code Playgroud)

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

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