C – 初始化结构数组

我在初始化结构数组时遇到问题。 我不确定我是否做得对,因为我得到“从不兼容的指针类型初始化”和“从不兼容的指针类型分配”。 我在代码中添加了这些警告,当我尝试从结构中打印数据时,我只是得到垃圾,例如@@ ###

typedef struct { char* firstName; char* lastName; int day; int month; int year; }student; 

//初始化数组

  student** students = malloc(sizeof(student)); int x; for(x = 0; x < numStudents; x++) { //here I get: "assignment from incompatible pointer type" students[x] = (struct student*)malloc(sizeof(student)); } int arrayIndex = 0; 

//添加struct

  //create student struct //here I get: "initialization from incompatible pointer type" student* newStudent = {"john", "smith", 1, 12, 1983}; //add it to the array students[arrayIndex] = newStudent; arrayIndex++; 

 student** students = malloc(sizeof(student)); 

不不不!

你不想要** 。 你需要一个*和足够的空间来容纳你需要的学生

 student* students = malloc(numStudents * sizeof *students); for (x = 0; x < numStudents; x++) { students[x].firstName = "John"; /* or malloc and strcpy */ students[x].lastName = "Smith"; /* or malloc and strcpy */ students[x].day = 1; students[x].month = 12; students[x].year = 1983; } 

与编译器警告无关,但您的初始malloc是错误的; 你要:

 malloc(sizeof(student *)* numStudents) 

为学生分配总共’numStudents’指针的空间。 这条线:

 students[x] = (struct student*)malloc(sizeof(student)); 

应该:

 students[x] = (student*)malloc(sizeof(student)); 

没有“结构学生”这样的东西。 你已经声明了一个未命名的结构,并将它定义为’student’。 比较和对比:

 struct student { char* firstName; char* lastName; int day; int month; int year; }; 

这将创建一个“结构学生”类型,但要求你(在C中)明确地引用结构学生而不仅仅是其他地方的学生。 对于C ++,此规则已更改,因此您的编译器可能会有点模糊。

至于:

 student* newStudent = {"john", "smith", 1, 12, 1983}; 

那应该是:

 student newStudent = {"john", "smith", 1, 12, 1983}; 

由于大括号语法是直接文字,而不是你需要指向的其他地方。

编辑:经过反思,我认为aaa可能比我有更多的概述。 是否有可能无意中在任何地方使用额外的指针解除引用? 所以你想要:

 student* students = malloc(sizeof(student) * numStudents); /* no need for this stuff: */ /*int x; for(x = 0; x < numStudents; x++) { //here I get: "assignment from incompatible pointer type" students[x] = (struct student*)malloc(sizeof(student)); }*/ int arrayIndex = 0; 

和:

 student newStudent = {"john", "smith", 1, 12, 1983}; //add it to the array students[arrayIndex] = newStudent; arrayIndex++; 

使数组不在newStudent范围之外使用。 否则将指针复制到字符串是不正确的。

 student* students = malloc(sizeof(student)*numStudents); int x; for(x = 0; x < numStudents; x++) { student newStudent = {"john", "smith", 1, 12, 1983}; // string copy are wrong still students[x] = newStudent; } 

在初始化时,不应该是这样的吗?

 student** students = (struct student**)malloc(sizeof(student*)*numStudents); 

但是,为什么指针指针? 只是用指向struct的指针就足够了。