I need to write a function that creates a double pointer using malloc.
This is how I declared my double pointer, as usual:
double **G; //Create double pointer to hold 2d matrix *G = malloc(numNodes * sizeof(double*)); for(i = 0; i < numNodes; i++) { G[i] = malloc(numNodes*sizeof(double)); for (j = 0; j < numNodes; j++) { G[i][j] = 0; } }
Now I tried replacing it with:
double **G; mallocDoubleArr(G, numNodes);
With function:
void mallocDoubleArr(double **arr, int size) { int i, j; *arr = malloc(size * sizeof(double*)); for(i = 0; i < size; i++) { arr[i]= malloc(size*sizeof(double)); for (j = 0; j < size; j++) { arr[i][j] = 0; } } }
Why is this not working?
You will need one more "indirectness", in other words, pass Gby reference as a pointer to a pointer to a pointer to a float:
G
void mallocDoubleArr(double ***arr, int size);
And then call him
mallocDoubleArr(&G, numNodes);
Change mallocDoubleArraccordingly, for example
mallocDoubleArr
(*arr)[i] = malloc(size*sizeof(double));
C is a call by value. IN
mallocDoubleArr. , - , , mallocDoubleArr.
, G-, . . , mallocDoubleArr double **.
double **G; G = mallocDoubleArr(numNodes); double **mallocDoubleArr(int size) { int i, j; double **arr; arr = (double **) malloc(size * sizeof(double *)); /* continue with old code */ return arr; }
[edit: bstamour post . .]
*G = malloc(numNodes * sizeof(double*));
G = malloc(numNodes * sizeof(double*));
( , -.)
-, , .
void mallocDoubleArr(double ***arr, int size)
, .
, , , , - , - . , ints, floats .., , : , . (int, float, pointer ..) , . .
int **inputMatrix, i, j; Grid myGrid = *grid; inputMatrix = (int *) calloc (myGrid.num_nodes, sizeof(int*)); for(i=0; i < myGrid.num_nodes; i++){ inputMatrix[i] = calloc(myGrid.num_nodes, sizeof(int)); for(j=0;j<myGrid.num_nodes;j++){ inputMatrix[i][j] = 0; } }; for(i=0; i < myGrid.num_nodes; i++){ free(inputMatrix[i]); } free (inputMatrix);