Andrew Lalis
Andrew Lalis

Reputation: 974

C Char Arrays Causing Segmentation Fault

I want to get the user to enter a series of lines that I read as chars, and save that into an array. I have a utility function that should print the value of each item in the grid. However, the line in printMaze() that uses putchar() is causing a segmentation fault, probably because something is messed up with the **maze argument, although I don't know what is causing it, or how to fix it. Here is the code below.

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

void printMaze(char **maze, int width, int height){
    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            putchar(maze[x][y]);
        }
    }
}

int main(int argc, char *argv[]){
    int width, height;
    scanf("%d %d", &height, &width);
    char originalMaze[width][height];
    for (int y = 0; y < height; y++){
        for (int x = 0; x < width; x++){
            originalMaze[x][y] = getchar();
        }
        getchar();
    }
    printMaze(originalMaze, width, height);
    return 0;
}

Upvotes: 1

Views: 132

Answers (1)

rgon91
rgon91

Reputation: 26

void printMaze(char **maze, int width, int height)

is looking for a pointer to a pointer, but you just supply a single pointer (original maze) in

printMaze(originalMaze, width, height);

Your compiler is probably passing the incompatible type anyway and letting the program start, but it won't work once you try loading the values into the array.

Upvotes: 1

Related Questions