简体   繁体   中英

Reading multi-line characters from a text file

I have to read a maze from a file and store it in a twodimensional array. The characters I'm reading are stored in a .txt file like this:

######
#....#
#..#.#
. .#..
######

Note that the number of rows and columns can vary depending on the file. My approach in reading the file so far:

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

void read_arr(char** a, int x_size, int y_size) {
    int i, j;
    int tmp;

    FILE* file = fopen("lab1.txt", "r");

    for (i = 0; i < y_size; i++) {
        for (j = 0; j < x_size; j++) {
            if (tmp = fgetc(file))
                a[j][i] = tmp;
            printf("Success\n");
        }
    }
}

void print_arr(char** a, int x_size, int y_size) {
    int i, j;

    for (i = 0; i < x_size; i++) {
        for (j = 0; j < y_size; j++) {
            printf("%c", a[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int x_size, y_size;

    printf("What is the size of the maze (<x> <y>)? "); 
    scanf("%d %d", &x_size, &y_size);
    printf("Maze has size %dx%d\n", x_size, y_size);

    char** a = malloc(sizeof(char) * (x_size * y_size));
    if (!a)
        return -1;

    printf("Successfully allocated memory!\n");

    read_arr(a, x_size, y_size);
    print_arr(a, x_size, y_size);
    return 0;
}

But all I get from this is a memory error (I'm afraid I cant't give the exact error message, because it is displayed in german). Another thing I've tried is using fscanf, but that didn't work either. I'm on Ubuntu, and using gcc to compile my code. Any help would be much appreciated!

Memory allocation is not correct

char** a = malloc(sizeof(char) * (x_size * y_size));

I guess what you wanted to do is

char** a = malloc(sizeof(char*) * y_size);
for(i = 0; i < y_size; ++i)
    a[i]=malloc(x_size);

Also in read_arr function, you access array as arr[j][i], while j is your inner index, and i is outer

for (i = 0; i < y_size; i++) {
    for (j = 0; j < x_size; j++) {
        if (tmp = fgetc(file))
            a[j][i] = tmp; ==> a[i][j] = tmp;
        printf("Success\n");
    }
}

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