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

时间:2015-03-02 23:01:30

标签: c arrays pointers malloc

我有一个设计用于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),返回指向数组的指针,并且生成的输出是相同的。

那是怎么回事?

如果需要,我可以包含一些示例数据或任何其他信息。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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