2015-03-02 89 views
3

我有一個函數設計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

回答

2

在更新的代碼中,您正在分配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

3

你的第二個循環是不正確的:

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