Short: How can I pass a 2D array as a function argument and get the results stored in the argument address?
Longer: I have code (below) which calls, from main()
an initialization function and then prints the content. However, I would expect that after storing the pointers given by malloc
into the variable A
the results would be saved in the argument but it does not. When doing similar things with 1D arrays it works smoothly but not for 2D arrays.
For simplicity, in this case I make it 3x3, but I want to have a non-fixed amount of GB of data. Then, I must use malloc
and I cannot declare the matrix size at compilation time.
#include <stdio.h>
#include <stdlib.h>
void print_matrix(int n, double **A) {
int i, j;
for(i=0; i<n; i++) {
for(j=0;j<n;j++) {
printf("%0.2f ",A[i][j]);
}
printf("\n");
}
}
void init(int n, double **A) {
int i;
A = (double **)malloc(n * n * sizeof(double *));
for(i=0; i<n; i++) {
A[i] = (double *)malloc(n * sizeof(double));
}
A[0][0] = 9.0;
A[0][1] = 6.0;
A[0][2] = -3.0;
A[1][0] = 6.0;
A[1][1] = 13.0;
A[1][2] = -5.0;
A[2][0] = -3.0;
A[2][1] = -5.0;
A[2][2] = 18.0;
print_matrix(n, A);
}
int main() {
int i;
int n=3;
double **A;
init(n, A);
print_matrix(n, A);
for(i=0; i<n; i++)
free(A[i]);
free(A);
return 0;
}
After compiling I can print the content of the matrix inside the init()
function but not from main()
without getting a segmentation fault, which of course means that A is pointing to unassigned memory and that not even A[0][0]
is pointing to the root of the matrix. I am using GCC and standard C99.
$ gcc --version
gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
$ gcc main.c -o main -std=c99
$ ./main
9.00 6.00 -3.00
6.00 13.00 -5.00
-3.00 -5.00 18.00
Segmentation fault (core dumped)
There are other useful questions about passing 2D arrays but they do not solve my point because they do not tackle the issue of getting the results back in the argument.
- C — passing a 2d array as a function argument?
- how to define a 2d array using malloc and pass it to a function fr
Edit: This is a simple case, but I would need to pass several matrices as function arguments. Therefore, I cannot simply return the address of the matrix A
, because I would need to save the addresses of several matrices.