返回我试图写入其中使用的功能来读取在阵列中的数据,存储的程序,并且然后试图阵列返回到主()用于分类处理。 这里就是我有访问阵列内容从功能
#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倍的值,什么shuold我在funcution数组的大小(我在程序的arr_count)传递给主()? 2.如果函数只返回数组的指针到main(),我可以计算出数组的大小吗?我该怎么办 ? Thans很多为您的助理。
C和C++语言。我相信你选择了前者。 –
你不需要函数中的'i'和'arr_count';他们总是有相同的价值。而你的缩进让你很难准确地读取你的代码;良好的缩进(并且完全排除制表符,特别是对于SO)使得读取代码变得容易。 –
可惜您在数组中分配了50个条目,但使用RESERVED_ARRAY_SIZE(又名100)测试了溢出。你做一个溢出测试;不幸的是,你发现这个问题太迟了。一致性在编程中非常重要;始终使用RESERVED_ARRAY_SIZE会有所帮助。调试使用'enum {RESERVED_ARRAY_SIZE = 100};'可能会更好,因为该符号将包含在调试符号表中(因此您可以执行'print RESERVED_ARRAY_SIZE'等),但宏值不会。 –