reshad reshad - 1 month ago 12
C Question

modifying double pointer to an integer array

void function(int **arr);

int main()
{
int *array;
array=calloc(4, sizeof(int));
function(&array);
return0;
}


void function(int **arr)
{
int *tmp;
tmp=calloc(4, sizeof(int));
tmp[0]=1;
tmp[1]=2;
tmp[2]=3;
tmp[3]=4;
}


I want to assign tmp to arr. how can I do it?

Answer

You should not do that because in this case there will be a memory leak because you already allocated memory for pointer array and the assignment will overwrite the value stored in the pointer. Write the function simpler

void function(int **arr)
{
    int *tmp = *arr;

    tmp[0]=1;
    tmp[1]=2;
    tmp[2]=3;
    tmp[3]=4;
}

Here is a demonstrative program

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

void init( int **a, size_t n, int value )
{
    int *tmp = *a;
    size_t i = 0;

    for ( ; i < n; i++ ) tmp[i] = value++;
}

void display ( int *a, size_t n )
{
    size_t i = 0;

    for ( ; i < n; i++ ) printf( "%d ", a[i] );
    printf( "\n" );
}

int main(void)
{
    int *a;
    size_t n = 4;

    a = calloc( n, sizeof( int ) );

    init( &a, n, 0 );
    display( a, n );

    init( &a, n, 10 );
    display( a, n );

    free( a );

    return 0;
}

The program output is

0 1 2 3 
10 11 12 13 

If you need to realloc the original array in a function then this can be done the followingway

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

void init( int **a, size_t n, int value )
{
    int *tmp = *a;
    size_t i = 0;

    for ( ; i < n; i++ ) tmp[i] = value++;
}

void display ( int *a, size_t n )
{
    size_t i = 0;

    for ( ; i < n; i++ ) printf( "%d ", a[i] );
    printf( "\n" );
}


void alloc_new( int **a, size_t n )
{
    int *tmp = malloc( n * sizeof( int ) );

    if ( tmp )
    {
        free( *a );
        *a = tmp;
    }   
}

int main(void)
{
    int *a;
    size_t n = 4;

    a = calloc( n, sizeof( int ) );

    init( &a, n, 0 );
    display( a, n );

    alloc_new( &a, n );

    init( &a, n, 10 );
    display( a, n );

    free( a );

    return 0;
}
Comments