我尝试使用指针在结构中创建二维数组,因为我是c的新手,并且对指针的主题感到困惑。请帮助!
struct course
{
char *coursecode;
char *coursesession[5];
};
int main()
{
int n = 0;
int numSession = 0;
struct course *main = malloc(sizeof(struct course));
printf("Enter the course code and the session in this order:");
scanf("%s", main->coursecode);
printf("Enter the number of session required:");
scanf("%d", &numSession);
for (int i = 0; i < numSession; ++i)
{
printf("Enter the session code (M1...):");
scanf("%s", main->coursesession[i]);
}
++n;
}
最佳答案
您已声明coursecode
为指向char
的指针,但是您需要为其分配空间,这可以使用malloc
进行。
并且您已声明coursesession
为5个指向char
的指针的数组。您需要再次使用malloc
为所有5个指针分配空间。
或者,您可以将它们都声明为数组,例如
struct course
{
char coursecode[100];
char coursesession[5][100];
};
这将
coursecode
声明为100个char
的数组,并且将coursesession
声明为5个100个char
数组的数组。显然,您可以将100
调整为所需的大小,但是无论如何,存储大小都是固定的。