我的程序的目的很简单,要从文件中读取整数序列,下面是代码:
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;
}
问题是,在外部函数(主函数)中,数组未更改。如何解决?
您需要按引用传递数组,以便函数可以更改其调用方的数组。
一定是:
process_file(FILE *file, int **arr, int *count)
像这样打电话:
process_file(file, &array, &count);
另外,我建议:
size_t
而不是int
数组长度。malloc()
。*array = malloc(*count * sizeof *array);
,这避免了重复int
。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句