简体   繁体   English

将数组传递给在arg-list中接受双指针的函数

[英]Passing an array to a function which accepts double pointer in arg-list

I want to pass newly defined array bool myArr[] = { false, false, true }; 我想传递新定义的数组bool myArr[] = { false, false, true }; to below existing function. 到现有功能以下。

void fun(bool** pArr, int idx)
{
    if(NULL == *pArr)
       return;

    (*pArr)[idx] = false;

    ...
    ...

    return;
}

I am not allowed to change anything in subroutine fun and I want to invoke the function by using the identifier myArr . 我不能改变任何东西子程序fun ,我希望通过标识符来调用函数myArr When I try fun(&myArr, 2); 当我尝试fun(&myArr, 2); I get below compilation error. 我得到以下编译错误。

no matching function for call to fun(bool (*)[3], int) 没有用于调用fun(bool (*)[3], int)匹配函数

candidates are: void fun(bool**, int) 候选者是:void fun(bool **,int)

One way I can think of is as below 我能想到的一种方法如下

bool* ptr = myArr;
fun(&ptr, 2);

But it looks dirty to me, please suggest a way to invoke fun my using the myArr 但这对我来说似乎很脏,请提出一种使用myArr调用fun我的myArr

Functions that want a pointer to a pointer typically expect a jagged array . 想要指向指针的函数通常需要一个锯齿状的数组 You can construct an array of arrays with a single element myArray , and pass that array to your function, like this: 您可以使用单个元素myArray构造一个数组数组,并将该数组传递给函数,如下所示:

bool *arrayOfPtrs[] = { myArray };
fun(arrayOfPtrs, 2);

This reads slightly better than your pointer solution, because creating an array of pointers eliminates the question of why you are creating a pointer to a pointer ( demo ). 这比您的指针解决方案读起来要好一些,因为创建指针数组消除了为什么要创建指向指针( demo )的问题。

This functions expects a pointer to a bool* , so the only way to call it is to have an actual bool* object somewhere. 该函数需要一个指向bool*的指针,因此调用它的唯一方法是在某个地方bool*一个实际的bool*对象。 Your solution is the only one. 您的解决方案是唯一的解决方案。

I would do a little differently. 我会做一些不同的事情。 I Think this is a bit cleaner: 我认为这比较干净:

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

Now I was playing with this in my c++14 and it didn't let me directly access the elements with an indexer. 现在我在c ++ 14中玩这个游戏,它不允许我使用索引器直接访问元素。 Maybe that changed at some point? 也许在某个时候改变了吗? But I thought this is reasonable. 但是我认为这是合理的。

Edit, this is really better: 编辑,这确实更好:

void fun3(bool pArr[], int idx)
{
    if (NULL == *pArr)
        return;

    pArr[idx] = false;

    return;
}

If you want to avoid using a hack every time you call the function you can simply write a wrapper function: 如果您想避免每次调用该函数时都使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM