0

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!

refl3x
  • 47
  • 3
  • 10
  • `char** a = malloc(sizeof(char) * (x_size * y_size));` allocates space for pointers, but not for data. – chux - Reinstate Monica Jan 12 '14 at 14:57
  • " I cant't give the exact error message, because it is displayed in german" -- I don't understand why that makes it impossible to give it. And why not just change the language locale? – Jim Balter Jan 12 '14 at 15:10
  • Here it is: "Speicherzugriffsfehler (Speicherabzug geschrieben)" – refl3x Jan 12 '14 at 15:14
  • Core was dumped (segmentation fault): http://stackoverflow.com/questions/19749206/cant-execute-shellcode-speicherzugriffsfehler-speicherabzug-geschrieben See how easy it is if you JUST USE THE EFFING GOOGLE? I mean really, people. – Jim Balter Jan 12 '14 at 15:31

1 Answers1

3

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");
    }
}
Dabo
  • 2,371
  • 2
  • 18
  • 26