将数组传递给在 arg-list 中接受双指针的函数
Passing an array to a function which accepts double pointer in arg-list
我想将新定义的数组bool myArr[] = { false, false, true };
传递到现有函数下方。
void fun(bool** pArr, int idx)
{
if(NULL == *pArr)
return;
(*pArr)[idx] = false;
...
...
return;
}
我不允许在子例程fun
中更改任何内容,我想使用标识符myArr
调用该函数。当我尝试fun(&myArr, 2);
时,出现以下编译错误。
调用
fun(bool (*)[3], int)
没有匹配函数候选人是: Void fun(bool**, int)
我能想到的一种方式如下
bool* ptr = myArr;
fun(&ptr, 2);
但是对我来说看起来很脏,请建议一种使用 myArr
调用fun
我
需要指向指针的指针的函数通常需要交错数组。你可以用单个元素myArray
构造一个数组数组,并将该数组传递给你的函数,如下所示:
bool *arrayOfPtrs[] = { myArray };
fun(arrayOfPtrs, 2);
这比指针解决方案读起来略好,因为创建指针数组消除了为什么要创建指向指针的指针的问题(演示)。
这个函数需要一个指向bool*
的指针,所以调用它的唯一方法是在某处有一个实际的bool*
对象。您的解决方案是唯一的解决方案。
如果你想避免每次调用函数时都使用 hack,你可以简单地编写一个包装函数:
void fun(bool** pArr, int idx)
{
if(NULL == *pArr)
return;
(*pArr)[idx] = false;
}
void super_fun(bool* pArr, int idx)
{
fun(&pArr, idx);
}
int main()
{
bool myArr[] = { false, false, true };
super_fun(myArr, 2);
}
我会做一些不同的事情。 我认为这更干净一些:
void fun2(bool * pArr, int idx)
{
*(pArr + idx) = true;
return;
}
int main(int argc, _TCHAR* argv[])
{
bool myArr[] = { false, false, true };
fun2(myArr, 1);
return 0;
}
现在我在我的 c++14 中使用它,它不允许我使用索引器直接访问元素。 也许在某个时候发生了变化? 但我认为这是合理的。
编辑,这真的更好:
void fun3(bool pArr[], int idx)
{
if (NULL == *pArr)
return;
pArr[idx] = false;
return;
}
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址