views:

414

answers:

4

I'm trying to pass a 2D array of char* into a function. I am getting this error:

"cannot convert 'char* (*)[2]' to 'char***' for argument '1' to 'int foo(char***)'"

Code:

int foo(char*** hi)
{
    ...
}

int main()
{
    char* bar[10][10];
    return foo(bar);
}
A: 

Would this be a bad time to introduce the concept of references?

Off hand, I would say that an extra '&' would be needed on the calling side. That being said, this is a dangerous game to play.

Why are you allocating this? Why is it on the stack? Why are you typing it to a char*** in the receiving function?

Jacob

TheJacobTaylor
A: 

try

int foo(char* hi[10][10])
{
}

int main()
{
    char* bar[10][10];
    return foo(bar);
}

Alternatively, use a reference, a vector of vectors or boost::multi_array.

drewster
I'd prefer not to use static array sizes for foo.
CookieOfFortune
@CookieOfFortune, Note that the first "10" is not respected by the compiler. The parameter has the same type as in my answer.
Johannes Schaub - litb
+3  A: 

Your array is an array of 10 char* arrays, each storing 10 char* pointers.

This means that when passing it to a function whose parameter is not a reference, it is converted to a pointer to an array of 10 char*. The correct function parameter type is thus

int foo(char* (*hi)[10])
{
    ...
}

int main()
{
    char* bar[10][10];
    return foo(bar);
}

Read further on this Pet peeve entry on Stackoverflow.

Johannes Schaub - litb
+1  A: 

If the size of your array is not going to change, you're better off using references to the array in your function. Its safer and cleaner. For example:

int foo(char* (&hi)[10][10] )
{
 int return_val = 0;
 //do something
 //hi[5][5] = 0;
 return return_val;
}

int main()
{
    char* bar[10][10];
    return foo(bar);
}
carleeto