简体   繁体   中英

c struct, malloc, realloc issue

as an exercise I wanted to create a function that generates a 2d array of structs that represent a tile (x, y, cost, type). I am using realloc and malloc heavily, but the output is not what I am expecting (for example the '#' character that represents a wall is being omitted). I can't find where the issue is :-/. Here is the code:

#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;
}

Any ideas what got wrong?

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

should be

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

and

switch (txt[i]) {

should be

switch (txt[m]) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM