如何使用指针将数组传递给函数

How do you pass an array to a function using pointers

我正在尝试使用按引用调用通过函数打印数组,但不断收到警告:

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

我尝试用 test(arr, n);test(*arr, n);test(&arr[], n);test(*arr[], n);test(&arr[], n);

替换 test(&arr, n);

但是没有任何效果,我做错了什么?

#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]);
    }
}

比那简单多了。在下面的示例中,我使用 size_t 来表示数组大小,它是一个无符号整数类型,专门用于此目的。

#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

只需使用数组元素类型的指针:

void test(int *a, int b);

如果您随后将数组传递给函数:

test(arr);

...C 编译器会将指向数组第一个元素 (&(arr[0])) 的指针传递给函数。

请注意,在这种情况下您不使用 &

函数内部可以使用数组操作:

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

(在你的情况下:printf("%d\n", arr[n]);

(除了 void * 之外的任何类型的指针数据类型都是如此。如果您对指针数据类型使用数组操作,C 编译器假定指针指向数组的第一个元素。 )

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

据我所知,函数参数中的[]不被解释为数组,而是被解释为指针。为此,...

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

... 解释为:

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

... 这意味着 C 编译器需要一个指向指针数组 (int *) 的指针,而不是指向整数数组 (int) 的指针。