Home > front end >  Passing an array of pointers to function in C
Passing an array of pointers to function in C

Time:09-26

What is the correct way to pass (and access) this particular array of pointers to a function? I have something like this, where ptr_arr will only point to some elements of arr:

void add_elements(int *A, int *B )
{
    int add = A[2]   B[2];
    printf("%d\n", add);
}

int main()
{
    int arr[] = { 10, 20, 30, 40, 50, 60 };
    int *ptr_array[] = {&arr[0], &arr[1], &arr[3]}

    int add_in_main  = arr[2]   *ptr_array[2];

    printf("%d\n", add_in_main);

    add_elements(arr, *ptr_array);

    return 0;
}

But when I try to access ptr_array[2] inside the function I obtain arr[2] instead of arr[3] whereas when I do the same operation inside main I get what I want. What am I missing?

CodePudding user response:

*ptr_array is exactly the same as ptr_array[0].

If you want to pass an array of pointers, remember that arrays decays to pointer to their first elements. So e.g. plain ptr_array is the same as &ptr_array[0], and its type will be int **.

So change your signature to accept that argument, and dereference the selected pointer in B:

void add_elements(int *A, int **B )
{
    int add = A[2]   *(B[2]);  // Added parentheses for clarity
    printf("%d\n", add);
}

Call as:

add_elements(arr, ptr_array);
  • Related