I am trying to create a multidimensional array in c. For testing purposes, I am trying to print the first element of the first row. The code seems to work up to that point; however, when I try to print the element a second time, I get a segmentation fault:
#include <stdbool.h>
#include <stdio.h>
typedef struct Matrix {
bool** elem;
int length;
} Matrix;
void generateMatrix(Matrix* m);
int main() {
Matrix m = {0, 0};
generateMatrix(&m);
fprintf(stdout, "%d ", m.elem[0][0]);
fprintf(stdout, "\n");
// Comment next line if you want it to work
fprintf(stdout, "%d ", m.elem[0][0]);
return 0;
}
void generateMatrix(Matrix* m) {
const int size = 2;
bool* ptrArray[size];
bool ptr1[] = {false, false};
bool ptr2[] = {true, true};
ptrArray[0] = ptr1;
ptrArray[1] = ptr2;
m->elem = ptrArray;
m->length = size;
}
I am using the gcc on ubuntu:
$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Why is this happening?