我尝试编写一个程序,该程序使用一个函数读取数据,存储在一个数组中,然后尝试将该数组返回到main()进行排序过程。这是我的资料
#include <stdio.h>
#include <stdlib.h>
#define RESERVED_ARRAY_SIZE 100
int* read_data_from_files()
{
int* arr = (int*) malloc(sizeof(int) * 50);
int arr_count;
int status;
int i,j ;
arr_count =0;
i=0;
FILE *cfPtr;
if ((cfPtr = fopen ("score.dat", "r"))== NULL)
{
printf("File cannot be opend\n");
}
else
{
fscanf(cfPtr, "%d", &arr[i]);
printf("%5d%5d\n", i, arr[i]);
while (!feof (cfPtr))
{
++i;
++arr_count;
status = fscanf(cfPtr, "%d", &arr[i]);
if (status == EOF)
{
break;
}
else if (status != 1)
{
fprintf (stderr, "Error input\n");
getchar();
}
if (arr_count >= RESERVED_ARRAY_SIZE)
{
fprintf(stderr, " The number of array is over.\n");
getchar();
}
printf("%5d%5d\n", i, arr[i]);
}
fclose (cfPtr);
}
printf("arr_count=%d\n", arr_count);
return arr;
}
int main()
{
int i;
int arr_count;
int* arr = (int*) malloc(sizeof(int) * 10);
arr = read_data_from_files();
arr_count = sizeof(arr)/sizeof(arr[0]);
printf("this check the size of array%d", arr_count);
for (i=0; i<9; i++)
{
printf("%d ", i);
printf("%d", *arr[i]);
}
selection_sort(arr, arr_count);
getchar();
return 0;
}我的问题是1.如果函数不能返回2个值,我应该怎么做才能将函数中的数组大小(程序中的arr_count )传递给main()?2.如果函数只返回数组的指针到main(),我能计算出main中数组的大小吗?我该怎么做?这对你的助手来说太多了。
发布于 2011-09-27 10:00:48
不,您不能自动计算出大小。返回多个值的标准方法是传递一个指向要在其中存储额外返回值的变量的指针:
int* read_data_from_files(int *result_size)
{
...
*result_size = arr_count;
...
return arr;
}
int main()
{
int arr_count;
int *arr = read_data_from_files(&arr_count);
...
}发布于 2011-09-27 10:05:07
您可以在main函数中创建一个变量size,并让函数调用将地址作为附加参数传递给read_data_from_files()。然后,read_data_from_files()可以从函数内部修改该值,您不需要返回它。
https://stackoverflow.com/questions/7563402
复制相似问题