So what I'm trying to do is create a two dimensional array as a matrix using pointers. I put a double pointer into my CreateMatrix function, along with rows/cols, and I dynamically allocate the arrays into them. I filled 10 into all of them to test, and it shows they're all allocated. However in main, when I try to access an arbitrary value of the 2D array, I segfault. Regardless of if it occurs in a function, shouldn't dynamically allocated be stored onto the heap, thus it should work?
void CreateMatrix(int ** matrix, int row, int col){
int i, j;
matrix = (int**)malloc(row* sizeof(int*));
for (i = 0; i < row; i++) {
matrix[i] = (int*)malloc(col* sizeof(int));
for (j = 0 ; j < col; j++) {
matrix[i][j] = 10;
printf("i: %d, j: %d\n", i,j);
printf("%d",matrix[i][j]);
}
}
}
In main:
int ** matrix1;
int m1row, m1col = 5;
CreateMatrix(matrix1, m1row, m1col);
fprintf(stdout,"Testing if got out");
fflush(stdout);
printf("This should be 10 : %d",matrix1[0][0]); //definitely segfaults here
Also, a side question; I was told that when passing 'by reference' in C, not only do you need pointers in the function definition, but an ampersand on the variable for the function call. Something like if I want to pass the matrix a by reference : CreateMatrix(&a, b, c);
instead of CreateMatrix(a, b, c);
. If I use an &, I get an incompatibility error saying the argument is a triple pointer,when I need a double pointer. (Which in theory makes sense, since you're passing the location of the double pointer). Then is & only used for non pointer variables?