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

标签 c dynamic-memory-allocation

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

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);

此外,我建议:

关于c - 将未初始化的数组传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672830/

相关文章:

delphi - Delphi 对象上的 Destroy 方法和 Finalize 方法有什么区别?

c++ - 如何为指针和动态内存分配定义模板?

c++ 什么是 "pointer = new type"而不是 "pointer = new type []"?

c - 局部变量的地址是否总是保证有效

c - NaN 在运行时如何保存?

c - InfluxDB 返回错误的时间戳。我不知道为什么

c - 插入排序不起作用

有效地创建一个新的排序文件,其中包含连续数字的旧未排序文件的内容

c - 交换动态分配的结构

c++ - 使用 realloc 增加大小与创建更大的动态数组