将未初始化的数组传递给 C 中的函数

Passing an uninitialized array to a function in C

我的程序的目的很简单,从文件中读取整数序列,代码如下:

int main()
{
   FILE *file = fopen("test.txt", "r");

   int *array = NULL; // Declaration of pointer to future array;
   int count;

   process_file(file, array, &count);

   return 0;
}

// Function returns 'zero' if everything goes successful plus array and count of elements as arguments
int process_file(FILE *file, int *arr, int *count)
{
    int a;
    int i;
    *count = 0;

    // Function counts elements of sequence
    while (fscanf(file, "%d", &a) == 1)
    {
        *count += 1;
    }

    arr = (int*) malloc(*count * sizeof(int)); // Here program allocates some memory for array

    rewind(file);

    i = 0;
    while (fscanf(file, "%d", &a) == 1)
    {
        arr[i] =  a;
        i++;
    }

    fclose(file);

    return 0;
}

问题是,在外部函数(main)中,数组没有改变。 如何解决?

您需要通过引用传递数组,以便函数可以更改其调用者的数组。

必须是:

process_file(FILE *file, int **arr, int *count)

然后这样调用:

process_file(file, &array, &count);

此外,我建议:

  • 数组长度使用 size_t 而不是 int
  • Not casting the return value of malloc().
  • 像这样计算大小:*array = malloc(*count * sizeof *array);,这样可以避免重复int