Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a function to malloc double pointer

Tags:

c

pointers

malloc

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?

like image 996
Ace Avatar asked Oct 22 '13 18:10

Ace


People also ask

What is the function of double pointer?

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.

What happens if you malloc a pointer twice?

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 .

How do I malloc a pointer?

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.


1 Answers

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));
like image 101
Some programmer dude Avatar answered Oct 07 '22 07:10

Some programmer dude