我正试图将值保存到一个动态分配的结构数组中。该程序在调用malloc的for循环中运行良好,并正确打印值,但一旦for循环结束,我尝试再次打印,它就会出错。
这是具有结构定义的标头
typedef struct{
char student_name[100];
int stdnt_id;
int courses[4];
int grades[4][10];
int number_courses;
}students;
typedef struct{
char course_name[100];
int course_id;
int course_students[100];
int number_students;
}courses;
typedef struct{
int number_courses;
int number_students;
}useful_numbers;
这就是代码。
#include <stdio.h>
#include <stdlib.h>
#include "structures.h"
useful_numbers numbers;
students **student;
courses **course;
void add_course(void)
{
putchar('n');
int x, y, z, new, tmp;
printf("How many courses are you adding? ");
scanf("%d", &new);
getchar();
tmp=numbers.number_courses;
if(numbers.number_courses>0)
{
courses **course=(courses **)realloc(course, sizeof(courses *)*(new+numbers.number_courses));
if(NULL==course)
{
printf("There was a problem in mallocn");
exit(1);
}
for(x=tmp; x<new+tmp; x++)
{
course[x]=(courses *)malloc(sizeof(courses));
if(NULL==course[x])
{
printf("There was a problem in mallocn");
exit(2);
}
printf("Print the name of course number %d: ", x+1);
gets(course[x]->course_name);
printf("Print the id number for %s: ", course[x]->course_name);
scanf("%d", &course[x]->course_id);
getchar();
numbers.number_courses++;
}
}
if(numbers.number_courses==0)
{
courses **course=(courses **)malloc(new*sizeof(courses *));
if(NULL==course)
{
printf("There was a problem in mallocn");
exit(3);
}
for(x=0; x<new; x++)
{
course[x]=(courses *)malloc(sizeof(courses));
if(NULL==course[x])
{
printf("There was a problem in mallocn");
exit(4);
}
printf("Print the name of course number %d: ", x+1);
scanf("%s", &course[x]->course_name);
getchar();
printf("Print the id for %s: ", course[x]->course_name);
scanf("%d", &course[x]->course_id);
getchar();
printf("%st%dt%dt%dn", course[x]->course_name, course[x]->course_id, numbers.number_courses, x);
numbers.number_courses++;
}
}
for(y=0; y<numbers.number_courses; y++)
{
printf("%dt%dn", course[y]->course_id, numbers.number_courses);
}
return;
}
在if
语句中,您声明了一个新的局部变量courses
,它隐藏了同名的全局变量:
courses **course=(courses **)malloc(....);
打印最终使用全局变量,但仍然是NULL
。相反,您希望设置现有的全局变量:
course=(courses **)malloc(....);