C结构体,malloc和realloc问题

3

作为一项练习,我想创建一个生成表示瓷砖(x、y、成本、类型)的结构体的2D数组的函数。我大量使用realloc和malloc,但输出结果不是我预期的(例如代表墙的“#”字符被省略了)。我找不到问题所在:-/。这是代码:

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

int COL, ROW;

struct Tile {
    int x;
    int y;
    int cost;
    char type[10];
};

struct Tile *** generate_map(char * txt) {
    int i, j, m;

    struct Tile ***col = (struct Tile***) malloc(sizeof (struct Tile**));
    struct Tile **row = (struct Tile**) malloc(sizeof (struct Tile*));
    struct Tile *t;

    i = j = m = 0;

    while (txt[m] != '\0') {

        if (txt[i] == '\n') {

            m++;
            col[j] = row;
            row = (struct Tile**) malloc(sizeof (struct Tile*));
            j++;
            i = 0;
            col = realloc(col, sizeof (struct Tile**) * (j + 1));
            continue;
        }

        t = (struct Tile*) malloc(sizeof (struct Tile));
        t->y = j;
        t->x = i;

        switch (txt[i]) {
            case '#':
                t->cost = 100;
                strcpy(t->type, "wall");
                break;
            case '.':
                t->cost = 5;
                strcpy(t->type, "sand");
                break;
            case ',':
                strcpy(t->type, "mud");
                t->cost = 10;
                break;
        }

        row[i] = t;
        i++;

        row = realloc(row, sizeof (struct Tile*) * (i + 1));
        m++;
    }

    COL = j;
    ROW = i;
    return col;
}

int main(int argc, char** argv) {
    char map[] = ".,.\n.,.\n.,.\n###\n.,.";

    int i, j;
    struct Tile ***k = generate_map(map);

    for (i = 0; i < COL; i++) {
        for (j = 0; j < ROW; j++) {
            printf("x:%d y:%d, cost: %d, type: %s \n", (k[i][j])->x, (k[i][j])->y, (k[i][j])->cost, (k[i][j])->type);
        }
    }


    return 0;
}

有什么想法是出了问题吗?
1个回答

4
   if (txt[i] == '\n') {

应该是

   if (txt[m] == '\n') {

并且

switch (txt[i]) {

应该是

switch (txt[m]) {

啊,确实,我太笨了。一直责怪错了东西。谢谢。 - fikson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接