为什么 calloc 函数不分配数组?

问题描述 投票:0回答:1

我正在尝试读取一个文件并用文件中的所有字符填充一个数组。问题是在 while 循环中执行停止并且出现分段错误。这是感兴趣的功能:

void allocAndFillArray(char **arrayChar, FILE *file) {
    // *file is checked before the function and 
    //  if the function is called the pointer is not NULL

    int len = x; // x is just a random size. In the real function it is the number of characters in the file
    *arrayChar = (char *)calloc(len, sizeof(char));

    int i = 0;
    while (i < len) {
        *arrayChar[i] = fgetc(file);
        i = i + 1;
    } // in this cycle the execution stops after the first iteration 
      // and only one character is written in the array 
      // before a crash reported as segmentation fault. 

   fclose(file);
}

我尝试用 malloc 更改 calloc,尝试更改大小但它不起作用

c malloc allocation calloc
1个回答
1
投票

为什么 calloc 函数不分配数组?

你没有检查

calloc()
是否成功,你应该。但更有可能的是,标题问题的答案是
calloc()
实际上分配数组。

问题是while循环中执行停止,出现segmentation fault错误

这几乎可以肯定是因为你的功能有问题。这里...

        *arrayChar[i] = fgetc(file);

...你似乎想要这个,而不是:

        (*arrayChar)[i] = fgetc(file);

他们不是一个意思。

[]
运算符和所有其他后缀运算符具有所有运算符的最高优先级,因此您的原始语句等同于

        *(arrayChar[i]) = fgetc(file);

,如果

*arraychar
达到超过一个非常小的数字,它几乎肯定会超出
i
指定的对象的边界——即使它达到 2 也可能,尽管这可能不足以触发段错误。

© www.soinside.com 2019 - 2024. All rights reserved.