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

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

本文关键字:指针 函数 arg-list 数组      更新时间:2023-10-16

我想将新定义的数组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;
}