C - 初始化结构数组

时间:2010-11-13 16:35:06

标签: c pointers struct malloc

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

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++;

4 个答案:

答案 0 :(得分:27)

这是不正确的:

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

答案 1 :(得分:7)

与编译器警告无关,但您的初始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;

};

这会创建一个'struct student'类型,但要求你(在C中)明确地引用struct student而不仅仅是其他地方的学生。对于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范围之外使用。否则将指针复制到字符串是不正确的。

答案 2 :(得分:3)

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

答案 3 :(得分:-1)

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

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

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