Search code examples
carrayspointersdynamic-memory-allocation

How to transmit pointer to dynamically allocated array as a function parameter


I want to allocate an array inside of a function and to be able to use the pointer to that array outside of it as well. I don't know what's wrong with my code

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

void alloc_array (int **v, int n)
{
    *v=(int *)calloc(n,sizeof(int));
    printf ("the address of the array is %p",v);
}

void display_pointer (int *v)
{
    printf ("\n%p",v);
}

int main()
{
    int *v;
    alloc_array(&v,3);
    display_pointer(v);

    return 0;
}

I would expect to get the same address in both printfs, but that is not the case. What is my mistake?


Solution

  • void alloc_array (int **v, int n)
    {
        *v = calloc(n,sizeof(int));
        printf("the address of the array is %p", *v);
        //                                   ----^
    }
    

    Note the additional star in my printf call.

    Also, don't cast the return value of malloc / calloc.