为什么我无法访问定位的内存?

时间:2015-09-09 14:32:12

标签: c memory memory-management

程序将数据从文件读取到数组,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;
}

1 个答案:

答案 0 :(得分:0)

请参阅下面的程序清单 - 我已修改您的代码,以便您将指针发送到指针ar ...现在可以正常工作。 @Johnny Mopp的评论很完美。

#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("zdata.txt","r");
   while(fscanf(fp,"%lf",&temp)==1)
       n++;
   fclose(fp);
   //load memory
   *ar = (double*)malloc(sizeof(double)*n);

   fp = fopen("zdata.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;
}