Reputation: 1197
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
Upvotes: 2
Views: 940
Reputation: 347
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;
}
Upvotes: 0
Reputation: 48675
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);
}
Upvotes: 0
Reputation: 727137
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).
Upvotes: 4
Reputation: 63174
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.
Upvotes: 1