加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 作为函数参数的指针数组

发布时间:2020-12-16 10:26:46 所属栏目:百科 来源:网络整理
导读:我对C/C++中的数组和指针有一个基本的问题. 说我有: Foo* fooPtrArray[4]; 如何将fooPtrArray传递给函数? 我试过了: int getResult(Foo** fooPtrArray){} // failedint getResult(Foo* fooPtrArray[]){} // failed 我该如何处理指针数组? 编辑:我曾经认
我对C/C++中的数组和指针有一个基本的问题.

说我有:

Foo* fooPtrArray[4];

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

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

我该如何处理指针数组?

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

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 * *到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);
}

解决方法

int getResult(Foo** fooPtrArray)

int getResult(Foo* fooPtrArray[])

以及

int getResult(Foo* fooPtrArray[4])

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

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

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

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

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

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

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

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读