指针数组作为函数参数

Lil*_*ily 4 c++ arrays pointers function

我对C/C++中的数组和指针有一个基本的问题.

说我有:

Foo* fooPtrArray[4];
Run Code Online (Sandbox Code Playgroud)

如何传入fooPtrArray函数?我试过了:

int getResult(Foo** fooPtrArray){}  //  failed
int getResult(Foo* fooPtrArray[]){} // failed
Run Code Online (Sandbox Code Playgroud)

我该如何处理指针数组?

编辑: 我曾经认为错误消息来自传递错误的指针数组,但是从所有响应中,我意识到它是另一回事......(指针赋值)

Error msg:
Description Resource Path Location Type incompatible types in assignment of 
`Foo**' to `Foo*[4]' tryPointers.cpp tryPointers line 21 C/C++ Problem
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它说:Foo**到Foo*[4].如果作为函数参数彼此互换,为什么在赋值期间,它会给出编译错误?

我尝试用最少的代码复制错误消息,如下所示:

#include <iostream>

using namespace std;

struct Foo
{
int id;
};

void getResult(Foo** fooPtrArray)
{
cout << "I am in getResult" << endl;
Foo* fooPtrArray1[4];
fooPtrArray1 = fooPtrArray;
}

int main()
{
Foo* fooPtrArray[4];
getResult(fooPtrArray);
}
Run Code Online (Sandbox Code Playgroud)

AnT*_*AnT 12

int getResult(Foo** fooPtrArray)
Run Code Online (Sandbox Code Playgroud)

int getResult(Foo* fooPtrArray[])
Run Code Online (Sandbox Code Playgroud)

以及

int getResult(Foo* fooPtrArray[4])
Run Code Online (Sandbox Code Playgroud)

将完美地工作(它们都是等价的).

你的问题不清楚是什么问题.什么"失败"?

当传递这样的数组时,通常也有理由传递元素数,因为允许数组类型延迟到指针类型的技巧通常专门用于允许传递不同大小的数组

int getResult(Foo* fooPtrArray[], unsigned n);
...
Foo* array3[3];
Foo* array5[5];
getResult(array3, 3);
getResult(array5, 5);
Run Code Online (Sandbox Code Playgroud)

但是如果你总是要传递严格的4个元素的数组,那么使用不同类型的指针作为参数可能是一个更好的主意

int getResult(Foo* (*fooPtrArray)[4])
Run Code Online (Sandbox Code Playgroud)

在后一种情况下,函数调用将如下所示

Foo* array[4];
getResult(&array);
Run Code Online (Sandbox Code Playgroud)

(注意&运算符应用于数组对象).

最后,由于这个问题被标记为C++,在后一种情况下,也可以使用引用而不是指针

int getResult(Foo* (&fooPtrArray)[4]);
...
Foo* array[4];
getResult(array);
Run Code Online (Sandbox Code Playgroud)