gpt4 book ai didi

c - 如何将内存分配给结构数组中的 typedef 结构

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:54 25 4
gpt4 key购买 nike

我一直在尝试为指针变量分配内存,但它一直给我错误或段错误。我如何正确地将指针变量初始化为类(class)结构?

 typedef struct {
char courseId[7];
char courseName[10];
} Course;

struct Student{
char firstName[10];
char lastName[10];
int studentId;
Course *course;
};

int main() {
int numStudents;
printf("How many students do you wish to register?: ");
scanf("%d", &numStudents);
struct Student *student[numStudents];
student[numStudents] = malloc(sizeof(*student[numStudents]));
student[numStudents]->course = malloc(sizeof*(numStudents * Course));
for (int i = 0; i < numStudents; i++) {
printf("Enter student #%d First Name: ", i+1);
scanf("%s", student[i]->firstName);
printf("Enter student Last Name: ");
scanf("%s", student[i]->lastName);
printf("Enter Student ID: ");
scanf("%d", &student[i]->studentId);
printf("Enter Course ID: ");
//student[i]->course = malloc(sizeof(*(student[i]->course)));
scanf("%s", student[i]->course->courseId);
printf("Enter Cousrse Name: ");
//student[i]->course = malloc(sizeof(*(student[i]->course)));
scanf("%s", student[i]->course->courseName);
}

for (int i = 0; i < numStudents; i++) {
printf("Student Name: %s %s\n", student[i]->firstName, student[i]->lastName);
printf("Student ID: %d\n", student[i]->studentId);
printf("Course Code: %s\n", student[i]->course->courseId );
printf("Course name: %s\n", student[i]->course->courseName);
free(student[i]->course);
}

最佳答案

您几乎完成了,需要进行一些更正。Student 中的 Course 对象不需要是指针。 Student 结构数组需要动态分配,然后再释放。 -> 用作取消引用运算符,但在您的情况下 [] 已经取消引用,因此您将使用 . 而不是 -> 当你为结构数组分配内存时,它需要结构的大小乘以结构的数量。 malloc(sizeof(struct Student)*numStudents);

typedef struct {
char courseId[7];
char courseName[10];
} Course;

struct Student{
char firstName[10];
char lastName[10];
int studentId;
Course course;
};

int main() {
int numStudents;
printf("How many students do you wish to register?: ");
scanf("%d", &numStudents);
struct Student* students = malloc(sizeof(struct Student)*numStudents);
for (int i = 0; i < numStudents; i++) {
printf("Enter student #%d First Name: ", i+1);
scanf("%s", students[i].firstName);
printf("Enter student Last Name: ");
scanf("%s", students[i].lastName);
printf("Enter Student ID: ");
scanf("%d", &students[i].studentId);
printf("Enter Course ID: ");
scanf("%s", students[i].course.courseId);
printf("Enter Cousrse Name: ");
scanf("%s", students[i].course.courseName);
}

for (int i = 0; i < numStudents; i++) {
printf("Student Name: %s %s\n", students[i].firstName, students[i].lastName);
printf("Student ID: %d\n", students[i].studentId);
printf("Course Code: %s\n", students[i].course.courseId );
printf("Course name: %s\n", students[i].course.courseName);
}
free(students);
return 0;
}

我尝试对您的代码进行最少的更改。

关于c - 如何将内存分配给结构数组中的 typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585143/

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