I need to write a function that creates a double pointer using malloc.
This is how I declared my double pointer as I normally would:
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 the function being:
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 doesn't this work?
The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.
It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr , which erases the old value that was in newPtr .
ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
You need one more "indirection", in other words pass G
by reference like a pointer to a pointer to a pointer to float:
void mallocDoubleArr(double ***arr, int size);
And then call it as
mallocDoubleArr(&G, numNodes);
Modify mallocDoubleArr
accordingly, like for example
(*arr)[i] = malloc(size*sizeof(double));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With