tsm
tsm

Reputation: 3

Segmentation fault with matrix in C

I'm a little rusty in C and I'm trying to initialize a matrix, but I'm getting some problems with it.Did some research but I couldn't find anything.

I get a segmentation fault at:

char **board;
board = (char **)malloc(N*N*sizeof(char));
board[0][0] = '.'; // segmentation fault here

I could be doing like:

char board[N][N] = '.';

but I need to pass the matrix to a function, by reference, but I'm getting errors too, so I tried to use double pointers right from the beginning.

Thank you.

Upvotes: 0

Views: 150

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409482

You have three choices:

  1. Allocate on the stack (or globally) like you don't want to do apparently. The error are probably because you think an array of arrays can be treated like a pointer to pointer, which it can not.

  2. Allocate dynamically, first the first dimension and for each row allocate the second dimension. You're missing the last step in your code.

  3. Allocate dynamically using a single dimension, like you do now, but use e.g. row * column_length + column as index.

Upvotes: 1

Related Questions