簡體   English   中英

c struct,malloc,realloc問題

[英]c struct, malloc, realloc issue

作為練習,我想創建一個函數,生成一個二維結構數組,表示一個tile(x,y,cost,type)。 我正在大量使用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]) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM