简体   繁体   中英

How do you pass an array to a function using pointers

I am trying to print an array through a function by using call by reference but keep getting a warning:

passing argument 1 of 'test' from incompatible pointer type [-Wincompatible-pointer-types]

I tried replacing test(&arr, n); with test(arr, n); , test(*arr, n); , test(&arr[], n); , test(*arr[], n); , test(&arr[], n);

but nothing worked, what am I doing wrong?

#include<stdio.h>
void test(int *a[], int b);
void main()
{
    int arr[]={1, 2, 3, 4, 5}, i, n=5;
    test(&arr, n);
}
void test(int *d[], int n)
{
    int i;
    for(i=0; i<n; i++)
    {
        printf("%d", *d[i]);
    }
}

It's much simpler than that. In the example below I'm using size_t to express array size, it's an unsigned integer type specifically meant to be used for that purpose.

#include <stdio.h>

// you can use the size parameter as array parameter size
void test (size_t size, int arr[size]); 

int main (void) // correct form of main()
{
    int arr[]={1, 2, 3, 4, 5};
    test(5, arr);
}

void test (size_t size, int arr[size])
{
    for(size_t i=0; i<size; i++) // declare the loop iterator inside the loop
    {
        printf("%d ", arr[i]);
    }
}

How do you pass an array to a function

Just by using a pointer of the array element type:

void test(int *a, int b);

If you then pass an array to the function:

test(arr);

... the C compiler will pass a pointer to the first element of the array ( &(arr[0]) ) to the function.

Note that you don't use the & in this case.

Inside the function you can use array operations:

void test(int * arr)
{
    arr[3] = arr[2];
}

(In your case: printf("%d\n", arr[n]); )

(This is true for any kind of pointer data type with exception of void * . The C compiler assumes that the pointer points to the first element of an array if you use array operations with pointer data types.)

"passing argument 1 of 'test' from incompatible pointer type"

As far as I know, [] in a function argument is not interpreted as array, but as pointer. For this reason, ...

void test(int *a[], int b);

... is interpreted as:

void test(int **a, int b);

... which means that the C compiler expects a pointer to an array of pointers ( int * ), not to an array of integers ( int ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM