Advertisement

quick question

Started by December 16, 2002 12:11 PM
2 comments, last by MetroidHunter 21 years, 11 months ago
How do I pass two dimensional arrays (one of type int, one an array of char strings) to a function in C?
You can''t. C passes arrays as pointers, which discard size information, including dimensionality. You need to pass the size as extra parameters and recompute the offset yourself : foo( int* arg, int cols ); ... args[r][c] becomes args[r*cols+c]

If you know the size of the array, define the type of your parameter to be an array instead of a pointer : foo( int arg[10][10] );. The leftmost size argument can be omitted : foo( int arg[][10] ) - the C compiler needs all but the leftmost to figure out the ''stride'', but doesn''t care about the total length, since it doesn''t do bounds-checking. Then you can directly use multi-dimensional indexing.

Finally, there is the trick of defining a multidimensional array as an array of arrays (i.e. an array of pointers), which is rather burdensome and may or may not be what you need... forum readers are quick enough to offer that solution as a cure-all, so I will abstain.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
Do I have to do anything different to pass it by address?
When you''re passing an array, you''re passing the address of its first element (thus, a pointer), which for static arrays is a constant. Even though this address is passed by value, you can modify the elements of the original array.

You can therefore consider that arrays are always passed ''by reference'', with the additional constraint that the base address of the array itself cannot be changed.

If you want to change the base address of the array, well, you need to use a dynamically allocated array (cf. malloc()), and pass a pointer to that pointer (essentially, an int**). Of course, once you do that you''ve got to handle all the memory management yourself, including making sure you get rid of the whole memory block.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement