【问题标题】:How do I create arrays within an array in C without a predefined size?如何在没有预定义大小的 C 中的数组中创建数组?
【发布时间】:2017-11-15 08:54:25
【问题描述】:

我想在 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': 未知大小

如何通过malloc在数组内成功创建数组?

【问题讨论】:

  • 什么数组?字符还是整数??首先使用int **a = malloc(sizeof(int *)*nbOfStudents);。你想要一个二维数组。
  • @Sarah Collins 你在这里大约三年了,到现在为止你这么糟糕吗?:)

标签: c arrays syntax malloc


【解决方案1】:

您可以使用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
}

【讨论】:

  • 您也可以使用int (*a)[noOfStudents] = malloc(sizeof *a * noOfItems); 来代替指针的VLA。
  • @mch 毫无疑问,只是另一种方法。
【解决方案2】:

您需要一个二维数组来保存整数项列表。你可以通过在整数指针上声明一个指针来做到这一点。

所以你要声明

int **a;

然后

printf("Please enter number of students\n");
if (scanf("%d", &noOfStudents)==0 && noOfStudents<=0)  // bonus: small safety
{
    printf("input error\n");
    exit(1);
}
// now we are sure that noOfStudents is strictly positive & properly entered
a = malloc(sizeof(int*)*noOfStudents);

然后你分配了指针数组,剩下的代码就OK了(不要转换mallocBTW的返回值)

变体是:

a = malloc(sizeof(*a)*noOfStudents);

(因此,如果a 的类型发生变化,则大小随之变化,在这里并不重要,因为它们都是指针)

【讨论】:

    【解决方案3】:

    使用指针代替数组,并使用malloccalloc 函数动态分配该指针的内存。

    像这样:

    int *a;
    
    a = malloc((sizeof(int)*noOfItems);
    

    【讨论】:

      【解决方案4】:

      你可以试试malloc函数,它动态分配内存并返回一个指向它的指针。然后可以将指针强制转换为指向特定类型数组的指针。

      【讨论】:

      • 从未听说过mallocate
      • 要么更新答案,要么删除它,这对任何人都没有好处。最好的是,它具有误导性且没有帮助。
      • 抱歉,打错了
      猜你喜欢
      • 2020-01-23
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 2013-01-19
      • 1970-01-01
      相关资源
      最近更新 更多