Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 初始化内部带有数组的结构数组_C_Arrays_Struct - Fatal编程技术网

C 初始化内部带有数组的结构数组

C 初始化内部带有数组的结构数组,c,arrays,struct,C,Arrays,Struct,因此,我创建了一个结构,其中包含一个未初始化的数组,但外部结构是一个已初始化的数组。然后我循环并打印这些值,但我什么也没有得到。NUM已定义为12 #include "header.h" #include <stdio.h> #include <stdlib.h> void make() { struct suit { char *type; int people[]; } deck[4] = {"Hunter", NUM, "Fighter

因此,我创建了一个结构,其中包含一个未初始化的数组,但外部结构是一个已初始化的数组。然后我循环并打印这些值,但我什么也没有得到。NUM已定义为12

#include "header.h"
#include <stdio.h>
#include <stdlib.h>


void make() {

struct suit {
    char *type;
    int people[];
} deck[4] = {"Hunter", NUM,
    "Fighter", NUM,
    "Jumper", NUM,
    "Strider", NUM};





};
//print type and numbers 1-12
for (int i = 0; i < 4; i++) {

    for (int j = 0; j < NUM; i++) {
        printf(deck[i].type);
        printf(deck[i].people[j]);

    }
}


}
#包括“header.h”
#包括
#包括
使无效{
结构诉讼{
字符*类型;
国际人士[];
}甲板[4]={“猎人”,数字,
“战士”,NUM,
“跳线”,NUM,
“漫游者”,NUM};
};
//打印类型和编号1-12
对于(int i=0;i<4;i++){
对于(int j=0;j
people
是一个灵活的数组成员,标准C不允许初始化灵活的数组成员。不过,GCC允许使用灵活的数组作为扩展。所以

 struct suit {
    char *type;
    int people[];
 } deck = {"Hunter", NUM};  
根据GCC,是有效的代码段,但同时当涉及灵活数组成员时,GCC不允许嵌套数组初始化,因此
deck[4]
的初始值设定项无效

当然,只有当额外数据位于顶级对象的末尾时,此扩展才有意义,否则我们将在后续偏移处覆盖数据。为了避免深度嵌套数组的初始化带来不必要的复杂性和混乱,我们只是不允许任何非空初始化,除非结构是顶级对象。例如:

 struct foo { int x; int y[]; };
 struct bar { struct foo z; };

 struct foo a = { 1, { 2, 3, 4 } };        // Valid.
 struct bar b = { { 1, { 2, 3, 4 } } };    // Invalid.
 struct bar c = { { 1, { } } };            // Valid.
 struct foo d[1] = { { 1, { 2, 3, 4 } } };  // Invalid. 

还请注意,对于不同的数据类型,您应该在
printf
中使用适当的格式说明符。

分配
int-people[]的内存数组,因此,您的结构应该如下所示,因为它是一个对象定义:

struct suit {
    char *type;
    int people[10]; //compile time allocation
} deck[4] = {"Hunter", NUM,
    "Fighter", NUM,
    "Jumper", NUM,
    "Strider", NUM};

你读过C的基础知识吗?您的
printf
错误。我认为你的代码甚至不能成功编译。你使用的是哪种编译器?你的代码能编译吗?我认为代码中存在多个问题。除了答案中指出的一个,printf没有任何格式说明符来打印整数。您的初始值设定项是非法的-编译器应该告诉您有一个问题您已经正确地认识到需要指定
人的大小,但是,您还需要为
组的每个元素支撑初始化器。否则,
“战斗机”
将作为
甲板[0]。人员[1]
的初始值设定项,依此类推。