Error passing 2D char* array into a function

て烟熏妆下的殇ゞ 提交于 2019-12-20 04:16:52

问题


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

回答1:


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.




回答2:


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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/1269216/error-passing-2d-char-array-into-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!