简体   繁体   中英

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 }; 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 . When I try fun(&myArr, 2); I get below compilation error.

no matching function for call to fun(bool (*)[3], int)

candidates are: 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

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:

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 ).

This functions expects a pointer to a bool* , so the only way to call it is to have an actual bool* object somewhere. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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