C struct、malloc、realloc 问题

标签 c

作为练习,我想创建一个函数来生成表示图 block (x、y、成本、类型)的二维结构数组。我大量使用 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;
}

有什么想法出了问题吗?

最佳答案

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

应该是

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

switch (txt[i]) {

应该是

switch (txt[m]) {

关于C struct、malloc、realloc 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788643/

相关文章:

c - c 中的指针算法和数组边界

c - 如何使用级数 sinx = x - (x3/3) 计算三角比! + (x5/5)i - (x7/7)! + 一个 C 程序

c - 'less' linux 命令的备用程序/使 'less' 安全

c++ - Makefile 只重新编译更改的对象?

c - 如何退出 "do-while"循环?

c - open() 在守护进程时返回错误

c - 实现线性搜索

c - 如何获取给定文件的 LBA 范围?

c - 为什么这个链表代码总是导致 head 为空?

c - 对于空终止字符串,strlen 有时等于 sizeof