简体   繁体   中英

How do I pass an array of arrays to a function?

I have an array of arrays and I need to pass it to a function. How would I do this?

int mask[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; 

How would the function signature look like?

I thought it would look like this

void foo(int mask[3][3])

or

void foo(int **mask)

but it seems that I am wrong and I couldn't find an example.

The least surprising way to pass arrays in C++ is by reference:

void foo(int (&mask)[3][3]);

Your first try

void foo(int mask[3][3])

should have worked, but it would be internally converted to

void foo(int (*mask)[3])

with unexpected implications for sizeof and other things that need a "real" array.

Your other idea int** doesn't work, because a 2-D dimensional array is not the same as an array of pointers, even though the a[i][j] notation works equally well for both.

If you don't want to share the content with the function (and see changes it might make), then none of the above will help. Passing a pointer by value still shares the target object. In that case you need to put the array inside another object, for example a std::array<std::array<int,3>,3>

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