我想在 C 中的数组中创建数组,而无需在数组中预定义数量的字符或输入。 以下是我的代码:
{
int noOfStudents,noOfItems;
int *grades;
int i;
char a[];
printf("Please enter number of students\n");
scanf("%d", &noOfStudents);
printf("Please enter number of items\n");
scanf("%d", &noOfItems);
for (i = 0; i < noOfStudents; i++)
{
a[i] = (int *)malloc((sizeof(int))*noOfItems);
}
我遇到了一个错误
c(2133): 'a': unknown size
如何通过malloc在数组中成功创建数组?
最佳答案
您可以使用 VLA (Variable length array) .
您需要重新排列代码,例如
int noOfStudents = -1, noOfItems = -1;
int *grades; //is it used?
int i;
printf("Please enter number of students\n");
scanf("%d", &noOfStudents);
//fail check
int *a[noOfStudents]; // this needs to be proper.
//VLA
printf("Please enter number of items\n");
scanf("%d", &noOfItems);
//fail check
for (i = 0; i < noOfStudents; i++)
{
a[i] = malloc(noOfItems * sizeof(a[i])); //do not cast
}
关于c - 如何在 C 中的数组内创建没有预定义大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303047/