从外部访问函数内部的函数 - 意外的结果

从外部访问函数内部的函数 - 意外的结果

问题描述:

我有一个函数设计malloc一个数组,然后用文件中的值(n维坐标,尽管现在在2d中工作)填充它。从外部访问函数内部的函数 - 意外的结果

#include <stdio.h> 
#include <stdlib.h> 

#define dim 2 

typedef struct { 
    double **array; /*store the coordinates*/ 
    int num; /* store the number of coordinates*/ 
    /* store some other things too */ 
} foo; 

void read_particles(foo *bar); 

int main(void) 
{ 
    foo bar; 

    read_particles(&bar); 

    printf("\n"); 
    for(int i = 0; i < bar.num; i++) 
     printf("%f %f\n", bar.array[0][i], bar.array[1][i]); 

    /* printf here does not output the array properly. 
    * Some values are correct, some are not. 
    * Specifically, the first column bar.array[0][i] is correct, 
    * the second column bar.array[1][i] is not, some values from the 
    * first column are appearing in the second. 
    */ 


    return 0; 
} 

void read_particles(foo *bar) 
{ 
    FILE *f = fopen("xy.dat", "r"); 

    /* read number of coordinates from file first*/ 
    fscanf(f, "%d", &bar->num); 

    bar->array = (double**) malloc(bar->num * sizeof(double*)); 
    for(int i = 0; i < bar->num; i++) 
     bar->array[i] = (double*) malloc(dim * sizeof(double)); 

    for(int i = 0; i < bar->num; i++) 
    { 
     for(int j = 0; j < dim; j++) 
      fscanf(f, "%lf", &(bar->array[j][i])); 

     /* For now, coordinates are just 2d, print them out 
     * The values are displayed correctly when printing here*/ 
     printf("%f %f\n", bar->array[0][i], bar->array[1][i]); 
    } 

    fclose(f); 
} 

Some sample data is available here.

当值是从它们是很好的在函数内部印刷,当它们不是函数外部打印。所以我不能正确处理指针。它可能(也可能不是)值得注意的是,我最初并没有使用一个结构,并且定义了double **read_and_malloc(num)的函数,将指针返回给数组,并且生成的输出是相同的。

那么是怎么回事?

我可以包括一些样本数据或任何其他信息,如果需要的话。

+0

与'bar-> num'相同吗? – 2015-03-02 23:04:18

+0

Dim是每个坐标的维数,bar.num是坐标的数量,所以最后我应该有数组[dim] [num]。 – Sam 2015-03-02 23:06:31

+0

换句话说.. *也许* ???你做了这个:'malloc(bar-> num * sizeof(double *))',后续的'for'循环最好使用一个不大于'bar-> num'的值,无论如何,作为相应的上限,否则你的代码将进入未定义的行为。 – WhozCraig 2015-03-02 23:07:19

在更新的代码中,您正在分配bar->num行和2列。但是,您的fscanfprintf代码尝试使用2行和bar->num列处理阵列。

为了让您的读/写代码不变,分配代码如下:

bar->array = malloc(dim * sizeof *bar->array); 
for (int i = 0; i < dim; ++i) 
    bar->array[j] = malloc(bar->num * sizeof *bar->array[j]); 

NB。如果你不熟悉这个malloc习惯用法,see here

+0

这似乎解决了这个问题,我会在早上彻底测试一下。谢谢。 – Sam 2015-03-03 00:34:34

你的第二个循环是不正确的:

for(int i = 0; i < dim; i++) 
    bar->array[i] = (double*) malloc(dim * sizeof(double)); 

创建bar->num元素但你遍历dim元素:

bar->array = (double**) malloc(bar->num * sizeof(double*)) 

回路应遍历第一维元素的个数: bar->num