Ton*_*ony 17 c malloc struct pointers
我在初始化结构数组时遇到问题.我不确定我是否做得对,因为我得到"从不兼容的指针类型初始化"和"从不兼容的指针类型分配".我在代码中添加了这些警告,当我尝试从结构中打印数据时,我只是得到垃圾,例如@@ ###
typedef struct
{
char* firstName;
char* lastName;
int day;
int month;
int year;
}student;
Run Code Online (Sandbox Code Playgroud)
//初始化数组
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;
Run Code Online (Sandbox Code Playgroud)
//添加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++;
Run Code Online (Sandbox Code Playgroud)
pmg*_*pmg 28
student** students = malloc(sizeof(student));
Run Code Online (Sandbox Code Playgroud)
不不不!
你不想要**.您需要*足够的空间来容纳您需要的学生
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;
}
Run Code Online (Sandbox Code Playgroud)
与编译器警告无关,但您的初始malloc是错误的; 你要:
malloc(sizeof(student *)* numStudents)
Run Code Online (Sandbox Code Playgroud)
为学生分配总共'numStudents'指针的空间.这条线:
students[x] = (struct student*)malloc(sizeof(student));
Run Code Online (Sandbox Code Playgroud)
应该:
students[x] = (student*)malloc(sizeof(student));
Run Code Online (Sandbox Code Playgroud)
没有"结构学生"这样的东西.你已经声明了一个未命名的结构,并将它定义为'student'.比较和对比:
struct student
{
char* firstName;
char* lastName;
int day;
int month;
int year;
};
Run Code Online (Sandbox Code Playgroud)
这将创建一个"结构学生"类型,但要求你(在C中)明确地引用结构学生而不仅仅是其他地方的学生.对于C++,此规则已更改,因此您的编译器可能会有点模糊.
至于:
student* newStudent = {"john", "smith", 1, 12, 1983};
Run Code Online (Sandbox Code Playgroud)
那应该是:
student newStudent = {"john", "smith", 1, 12, 1983};
Run Code Online (Sandbox Code Playgroud)
由于大括号语法是直接文字,而不是你需要指向的其他地方.
编辑:经过反思,我认为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;
Run Code Online (Sandbox Code Playgroud)
和:
student newStudent = {"john", "smith", 1, 12, 1983};
//add it to the array
students[arrayIndex] = newStudent;
arrayIndex++;
Run Code Online (Sandbox Code Playgroud)
使数组不在newStudent范围之外使用.否则将指针复制到字符串是不正确的.