1

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);
}
CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58

4 Answers4

5

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.

Community
  • 1
  • 1
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1

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);
}
Carl
  • 43,122
  • 10
  • 80
  • 104
0

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
  • 4,063
  • 1
  • 21
  • 23
0

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.

Andrew Prock
  • 6,900
  • 6
  • 40
  • 60