Following the advice of the C FAQ on creating a matrix instance using a double pointer , I came across another problem. I managed to solve the problem, but I hardly understand why it works in one direction, but not in the other.
I have the following code that works, and then I will show you a bit that does not work, and I hope you can explain why:
#include <stdio.h>
#include <stdlib.h>
int HEIGHT = 20;
int WIDTH = 20;
int ** curr_grid;
int ** create_grid() {
int ** grid;
grid = malloc(sizeof(int *) * HEIGHT);
int row;
for (row = 0; row < HEIGHT; row++)
grid[row] = malloc(sizeof(int) * WIDTH);
return grid;
}
int main(int argc, char** argv) {
curr_grid = create_grid();
curr_grid[0][0] = 0;
free(curr_grid);
return 0;
}
Allocates memory for the grid and returns a pointer this way. However, I first tried another method, which, as I was convinced, should work, too, but this is not so:
#include <stdio.h>
#include <stdlib.h>
int HEIGHT = 20;
int WIDTH = 20;
int ** curr_grid;
create_grid(int ** grid) {
grid = malloc(sizeof(int *) * HEIGHT);
int row;
for (row = 0; row < HEIGHT; row++)
grid[row] = malloc(sizeof(int) * WIDTH);
}
int main(int argc, char** argv) {
create_grid(curr_grid);
curr_grid[0][0] = 0;
free(curr_grid);
return 0;
}
This method completes with a segmentation error on the specified line. However, I got the impression that passing a variable by reference allows you to modify it.
?