我正在尝试使用指针在结构中创建一个二维数组,因为我是 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
调整为您需要的任何值,但无论如何存储大小都将是固定的。
关于c - struct-C 中字符串的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027617/