gpt4 book ai didi

C - 初始化结构数组

转载 作者:太空狗 更新时间:2023-10-29 16:30:23 31 4
gpt4 key购买 nike

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

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;

//添加结构

 //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); // or sizeof (student)
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;
}

如果您仍想使用“//add struct”部分中的代码,则需要更改以下行:

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

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

您收到“从不兼容的指针类型进行初始化”,因为您试图使用类型为 student 的对象初始化指向 student 的指针。

关于C - 初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4173518/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com