Search code examples
carrayspointersdouble-pointer

modifying double pointer to an integer array


I have a pointer to an int *array, I allocated it and then pass it to a function in order to fill in the elements of the 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?


Solution

  • You don't need to calloc array in main, first of all. It's a pointer and all you need to do is assign tmp to it. Here's how:

    void function(int **arr);
    
    int main()
    {
        int *array;
        size_t i;
    
        function(&array);
        // do stuff with array
        for (i = 0; i < 4; i++)
        {
            printf("%d\n", array[i]);
        }
        // then clean up
        free(array);
    
        return 0;
    }
    
    
    void function(int **arr)
    {
        int *tmp;
        tmp=calloc(4, sizeof(int));
        tmp[0]=1;
        tmp[1]=2;
        tmp[2]=3;
        tmp[3]=4;
    
        *arr = tmp;
    }