我正在尝试访问课程结构的课程名称成员,因此我可以在Read_courses函数的底部存储一个字符串。什么是正确的格式?我尝试过ptr [0] .course_name,以及其他我能想到的其他格式,但是Visual Studio总是在各处抛出错误。谢谢。
typedef struct course
{
char* course_name; //stores course name
int num_sections; //number of sections
student** sections;//stores array of student arrays(2D array). Size is num_sections;
int* num_students;//stores array of number of students in each section. Size is num_sections;
int* num_scores; //stores array of number of assignments in each section. Size is num_sections;
} course;
course* read_courses(FILE* fp, int* num_courses)
{
char Course_Name_Temp[10];
printf("Allocating memory to %d courses...\n\n", *num_courses);
course* ptr = (course*)malloc(*num_courses * sizeof(course));
if (ptr != NULL)
printf("Allocation sucessful, %d bytes allocated!\n\n", *num_courses * sizeof(*ptr));
(void)fscanf(fp, "%s", Course_Name_Temp);
strcpy(ptr[0].course_name, Course_Name_Temp);
printf("The first course name is %s\n\n", ptr[0].course_name);
}
您已经为course
数组分配了内存。那很好。您没有为每个course_name
分配内存,而是尝试写入其中一个。不好。
您可以按如下方式为字符串分配空间:
ptr[0].course_name = malloc(strlen(Course_Name_Temp)+1);