我有一個函數設計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)
的函數,將指針返回給數組,並且生成的輸出是相同的。
那麼是怎麼回事?
我可以包括一些樣本數據或任何其他信息,如果需要的話。
與'bar-> num'相同嗎? – 2015-03-02 23:04:18
Dim是每個座標的維數,bar.num是座標的數量,所以最後我應該有數組[dim] [num]。 – Sam 2015-03-02 23:06:31
換句話說.. *也許* ???你做了這個:'malloc(bar-> num * sizeof(double *))',後續的'for'循環最好使用一個不大於'bar-> num'的值,無論如何,作爲相應的上限,否則你的代碼將進入未定義的行爲。 – WhozCraig 2015-03-02 23:07:19