Read a file to a 2D array in C

前端 未结 2 652
暗喜
暗喜 2021-01-27 22:52

I\'m learning C and I decided to make a text game as my learning project. So I\'m trying this primitive \"parser\" that reads a text file into a 2D array, but there\'s

相关标签:
2条回答
  • 2021-01-27 23:35

    The main problem is that

    char *map[ROWS][COLS];
    

    only allocates space for ROWS x COLS char pointers, it does not allocate space for the strings themselves. So you're continually overwriting charbuffer as you've done it with every iteration, which explains why you end up with the same characters repeated over and over when you read out. You need to dynamically allocate the memory you need, along the lines of

    for (row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++) {
            charbuffer = (char*)malloc(sizeof(char) * 3);  //****
            map[row][col] = fgets(charbuffer, 3, mapfile);
        }
    }
    
    0 讨论(0)
  • 2021-01-27 23:44

    You should have strdup'ed the contents read from the file. Replace the file reading block with this:

    /* Reading file into array */
    for (row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++) {
            if (fgets(charbuffer, 3, mapfile))
                map[row][col] = strdup(charbuffer);
        }
    }
    

    and don't forget to put this at the beginning of your code too:

    #include <string.h>
    
    0 讨论(0)
提交回复
热议问题