c - 如何在 C 中的数组内创建没有预定义大小的数组?

标签 c arrays syntax malloc

我想在 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/

相关文章:

c - 如何将无符号 24 位 int 转换为有符号 int 并将符号扩展为 32 位?

c - 为什么我会收到此内存访问错误 'double free or corruption'?

arrays - 将不同格式的 'dates' 转换为 ruby​​ 中的特定格式

python : How and why is this syntax working ? {1,2,3,4}

Java 原始声明

c - 一个简单的C switch 语句程序错误。我无法构建和运行它。我不知道为什么

java - 使用 bigInteger 和其他方法重建字节数组

java - 单击时不显示微调器

javascript - 将非法 token 传递给 JavaScript 函数?

c++ - C/C++ 应用程序中嵌入式 SQL 数据库的 PostgreSQL 替代品