Dynamic Memory Allocation through Double Pointer and Function without returning address

In this tutorial, we will see how to allocate memory on a heap through a function without returning the address of allocated memory. In other words, we want to indirectly assign the address of allocated memory to a pointer. This pointer will define inside the main function.

#include <stdio.h>
#include <stdlib.h>

void allocate(int **a){
    *a = (int*)malloc(sizeof(int)*10);
}
int main(){
    int *p = NULL;
    allocate(&p);
    for(int i=0; i<=9; i++)
    *(p+i) = i;
    for(int i=0; i<=9; i++)
    printf("%d\n", *(p+i));
    return 0;
}

The function allocate(int **a) allocates memory for 10 integer elements on the heap and assigns the address of the first element to local pointer p.

Debug code with printf


#include <stdio.h>
#include <stdlib.h>

void allocate(int **a){
    printf(" Value of local double pointer **a = %d\n",a);
    *a = (int*)malloc(sizeof(int)*10);
}
int main()
{
    int *p = NULL;
    printf(" Address of Pointer 'p' = %d \n",&p);
    printf(" Value of Pointer 'p' before calling allocate() = %d\n", p);
    allocate(&p);
    
    printf(" Value of Pointer 'p' after calling allocate() = %d\n", p);
    for(int i=0; i<=9; i++)
    *(p+i) = i;
    for(int i=0; i<=9; i++)
    printf("%d", *(p+i));

    return 0;
}

Code output:

Address of Pointer 'p' = 1497023624 
Value of Pointer 'p' before calling allocate() = 0
Value of local double pointer **a = 1497023624
Value of Pointer 'p' after calling allocate() = 23445520
0123456789

Function to Allocate Memory on Heap through Double Pointer without Returning Address

Leave a Comment