将未知大小的结构数组传递给函数并填充

时间:2017-02-04 19:15:19

标签: c arrays struct

首先,我承认我对C和指针知之甚少,但我一直在阅读并且尚未找到解决方案。我也尝试过在SO上找到的一些解决方案,但没有一个有效。

从文件中读取填充结构的信息以及数组的大小。所以,我想在main()中声明数组,用于进一步处理,并通过引用传递给它read_p5_info(),在那里初始化和填充它。 'configs'将由configurations()函数填充。

typedef struct pentomino_info pentomino_info; 

struct pentomino_info {
    char name;
    int orientations;
    int blocks[5][2];
    int configs[8];
};

int read_p5_info(int *npieces, int *matrix_size, pentomino_info **pieces) {
    // piece info is read from file
    // npiece and matrix_size are also read from the file
    // With file I'm testing with, npieces = 12 and matrix_size = 5

    *pieces = malloc(*npieces * sizeof *pieces);

    for (p = 0 ; p < *npieces ; p++) {
        pieces[p] = malloc(sizeof *pieces[p]);

        ret = fscanf(fp, "%c %*d %d %d %*d %*d %*f", &pieces[p]->name, &p5_rotations, &p5_flips);

        pieces[p]->orientations = p5_rotations * p5_flips;

        // read p5 blocks
        int b = 0;
        for (l = *matrix_size - 1 ; l >= 0 ; l--) {
            for (c = 0 ; c < *matrix_size ; c++) {
                // p5_char is a char read from the file
                if(p5_char == '#' || p5_char == 'X') {
                    pieces[p]->blocks[b][0]=c;
                    pieces[p]->blocks[b][1]=l;
                    b++;
                }
            }
        }
    }

    return 0;
}

int main() {
    int npieces, matrix_size;
    pentomino_info *pieces; // array of p5 pieces

    int ret;

    ret = read_p5_info(&npieces, &matrix_size, &pieces);

    // configurations() operates on each piece individually
    configurations(matrix_size, &pieces[k]);
}

我所谈论的是Pentominos npieces 是文件具有信息的pentaminos的数量, matrix_size 是因为 pentamino_info.blocks 具有每个块的位置的坐标X,Y在 matrix_size x matrix_size 矩阵中。

我在main()的末尾得到段错误件[0] 看起来很好,但仍然让我发生了段错误,其他人只是格格不入。

我尝试通过删除一些似乎不相关的部分来使代码更紧凑,如果我过度使用,请告诉我。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

*pieces = malloc(*npieces * sizeof *pieces);分配错误的内存量。应该是sizeof **pieces。该模式为P = malloc(N * sizeof *P);作为认知交叉检查,检查sizeof参数前面还有一颗星。

pieces[p]->x应为(*pieces)[p].x,您可以在多个位置犯这个错误。在数组表示法中,您编写了pieces[p][0].x,但正确的索引是pieces[0][p].x。指针pieces仅指向一个指针,然后指向信息数组的第一个元素。

如果这令人困惑,我建议在你的函数中使用“普通”指针,然后在结尾处实现返回引用,例如:

int n_pie = 12;  // or whatever you read

pentomino_info *pie = malloc(n_pie * sizeof *pie);
// ...
pie[p].orientations = bla;
// ...

*npieces = n_pie;
*pieces = pie;
return 0;