I am trying to pass a matrix by reference and then initialize it dynamically. This is just an example:
int main(int argc, char* argv[]) {
int** matrix = NULL;
initialize(&matrix, 8);
return 0;
}
void initialize(int*** matrix, int size) {
*matrix = (int**) calloc(size, sizeof(int*));
for (int i = 0; i < size; ++i) {
*matrix[i] = (int*) calloc(size, sizeof(int)); // cashes here with segmentation fault
}
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
*matrix[i][j] = 5; // some number, doesn't matter for now
}
}
}
I have also tried the alternative, saving the matrix in a contiguous memory space:
*matrix = (int**) calloc(size, sizeof(int*));
*matrix[0] = (int*) calloc(size * size, sizeof(int));
for (int i = 1; i < size; ++i) {
*matrix[i] = *matrix[0] + size * i; // crashes here, segmentation fault
}
Yet the same error pops. Never on index 0, always on index 1. I don't understand, what am I doing wrong?
Any kind of help will be greatly appreciated!
Kind regards, Raul.