Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在没有预定义大小的情况下在C中的数组中创建数组?_C_Arrays_Syntax_Malloc - Fatal编程技术网

如何在没有预定义大小的情况下在C中的数组中创建数组?

如何在没有预定义大小的情况下在C中的数组中创建数组?,c,arrays,syntax,malloc,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");

我希望在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);
    }
{
国际NoofStudent、noOfItems;
国际*职等;
int i;
字符a[];
printf(“请输入学生人数”\n);
scanf(“%d”、&noofstudent);
printf(“请输入项目数量\n”);
scanf(“%d”和“noOfItems”);
对于(i=0;i
我犯了一个错误

c(2133):“a”:未知大小


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

使用指针而不是数组,并使用
malloc
calloc
函数动态分配该指针的内存

像这样:

int *a;

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

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

您可以使用

您需要像这样重新排列代码

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 noOfStudents=-1,noOfItems=-1;
int*grades;//是否使用它?
int i;
printf(“请输入学生人数”\n);
scanf(“%d”、&noofstudent);
//失败检查
int*a[noOfStudents];//这需要适当。
//弗拉
printf(“请输入项目数量\n”);
scanf(“%d”和“noOfItems”);
//失败检查
对于(i=0;i
您需要一个二维数组来保存整数项列表。您可以通过在整数指针上声明指针来实现这一点

你想申报吗

int **a;
然后


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

什么数组?char或int??使用
int**a=malloc(sizeof(int*)*nbOfStudents)首先。你想要一个二维数组。@Sarah Collins你在这里大约三年了,到现在你还这么坏吗?:)从来没有听说过
mallocate
要么更新答案,要么删除它,这对任何人都没有好处。最好的是,这是误导性的,没有帮助。对不起,这是一个输入错误你也可以使用
int(*a)[noOfStudents]=malloc(sizeof*a*noOfItems);
而不是指针的VLA。@毫无疑问,mch只是另一种方法。
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);
a = malloc(sizeof(*a)*noOfStudents);