指针数组作为函数参数 [英] array of pointers as function parameter

查看:32
本文介绍了指针数组作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a basic question on array and pointer in C/C++.

说我有:

Foo* fooPtrArray[4];

如何将 fooPtrArray 传递给函数?我试过了:

How to pass the fooPtrArray into a function? I have tried:

int getResult(Foo** fooPtrArray){}  //  failed
int getResult(Foo* fooPtrArray[]){} // failed

如何处理指针数组?

我曾经认为错误消息是由于传递了错误的指针数组,但是从所有响应中,我意识到它是别的东西......(指针分配)

I once thought the error msg is from passing the wrong pointer array, but from all the responses, I realize that it's something else... (pointer assignment)

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

我不太明白为什么它说:Foo* * to Foo*[4].如果作为函数参数,它们是相互交换的,为什么在赋值时,它给我编译错误?

I don't quite get why it says: Foo* * to Foo*[4]. If as function parameter they are inter-change with each other, why during assignment, it give me compilation error?

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

I tried to duplicate the error msg with minimum code as follows:

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

推荐答案

两者

int getResult(Foo** fooPtrArray)

int getResult(Foo* fooPtrArray[])

以及

int getResult(Foo* fooPtrArray[4])

将工作得很好(它们都是等价的).

will work perfectly fine (they are all equivalent).

从您的问题中不清楚问题出在哪里.什么失败"?

It is not clear from your question what was the problem. What "failed"?

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

When passing arrays like that it normally makes sense to pass the element count as well, since the trick with allowing the array type to declay to pointer type is normally used specifically to allow passing arrays of different sizes

int getResult(Foo* fooPtrArray[], unsigned n);
...
Foo* array3[3];
Foo* array5[5];
getResult(array3, 3);
getResult(array5, 5);

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

But if you always going to pass arrays of strictly 4 elements, it might be a better idea to use a differently-typed pointer as a parameter

int getResult(Foo* (*fooPtrArray)[4])

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

In the latter case the function call will loook as follows

Foo* array[4];
getResult(&array);

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

(note the & operator applied to the array object).

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

And, finally, since this question is tagged as C++, in the latter case a reference can also be used instead of a pointer

int getResult(Foo* (&fooPtrArray)[4]);
...
Foo* array[4];
getResult(array);

这篇关于指针数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆