行 *array[cnt] = thing
导致段错误,我不知道为什么。有解决此问题的想法吗?
long *Load_File(char *Filename, int *Size)
{
FILE *fp;
if((fp = fopen(Filename,"r")) == NULL)
{
printf("Cannot open file.\n");
exit(-1);
}
fscanf(fp,"%d",Size);
int cnt = 0;
int items = *Size;
long * array[items];
int thing;
while (!feof(fp))
{
fscanf(fp,"%d",&thing);
*array[cnt] = thing;
cnt++;
}
fclose(fp);
return *array;
}
最佳答案
long * array[items];
声明了一个指向 long 数据类型的指针数组。但是这些指针没有指向任何有意义的东西。
当你做的时候
*array[cnt] = thing;
你取消引用了不正确的指针,因为它们没有指向任何有意义的东西。
您可以为数组动态分配内存:
long * array = (long*) malloc(size(long) * items);
然后做:
while (!feof(fp)) {
fscanf(fp,"%d",&arr[cnt++]);
}
然后将数组返回为:
return array;
关于C编程指针数组读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2234349/