[英]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
我的myArr
该函数需要一个指向bool*
的指针,因此调用它的唯一方法是在某个地方bool*
一个实际的bool*
对象。 您的解决方案是唯一的解决方案。
我会做一些不同的事情。 我认为这比较干净:
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;
}
如果您想避免每次调用该函数时都使用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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.