程序将数据从文件读取到数组,load_data
将数据加载到数组 ar
。但是为什么我会得到 Segmentation fault (core dumped)
当我访问 main
中的该数组时.
#include <stdio.h>
#include <stdlib.h>
long int load_data(double * ar);
int main(void)
{
long int n,i;
double * ar;
FILE * fp;
double number;
n=load_data(ar);
fp = fopen("data-copy.txt","w");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
for(i=0; i<n; i++)
fprintf(fp,"%lf\n", ar[i]); //problem here! I can't access!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
fclose(fp);
printf("The number of elements in the file is:%ld\n",n);
}
long int load_data(double * ar)
{
FILE * fp;
double temp;
long int n=0,i;
fp = fopen("data.txt","r");
while(fscanf(fp,"%lf",&temp)==1)
n++;
fclose(fp);
//load memory
ar = (double*)malloc(sizeof(double)*n);
fp = fopen("data.txt","r");
for(i=0; i<n; i++)
{
fscanf(fp,"%lf",ar+i);
// printf("%lf\n",ar[i]);//This print well!
}
fclose(fp);
return n;
}
最佳答案
C 中的所有函数参数都是按值传递。
你的main
函数复制ar
的值(垃圾值)到编译器放置函数参数的地方(通常在指定的寄存器或在堆栈上)。
在函数 load_data
中,ar
的副本更改为指向内存块的指针,但原始 ar
位于main
没有改变并且仍然是垃圾。
当您退出该函数时,您将丢弃 ar 的副本(泄漏 malloc block )。然后你尝试取消引用原始的ar
,它仍然是垃圾。
关于c - 为什么我无法访问所定位的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482419/