In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be ?
In addition my multidimensional array may contain types other than strings.
original title: "Passing multidimensional arrays as function arguments in C"
In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be ?
In addition my multidimensional array may contain types other than strings.
Cでは、配列の次元がどうなるかわからないときに、多次元配列を単一の引数として関数に渡すことができますか?さらに、私の多次元配列には...
これは翻訳後の要約です。完全な翻訳を表示する必要がある場合は、「翻訳」アイコンをクリックしてください。
You can do this with any data type. Simply make it a pointer-to-pointer:
But don't forget you still have to malloc the variable, and it does get a bit complex:
The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)
Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:
Call this function with:
Output:
Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int:
which would be called as
Same principle applies for higher-dimension arrays:
You can declare your function as:
The compiler will then do all pointer arithmetic for you.
Note that the dimensions sizes must appear before the array itself.
GNU C allows for argument declaration forwarding (in case you really need to pass dimensions after the array):
The first dimension, although you can pass as argument too, is useless for the C compiler (even for sizeof operator, when applied over array passed as argument will always treat is as a pointer to first element).