In both C and C++, you cannot either pass an array as an argument to a function, or return an array as a function result.
Yes, the syntax can make it look like you're passing an array argument:
void func(int param[]) {
// ...
}
...
int arr[10];
func(arr);
but in fact that's just passing a pointer to the array's first element. The parameter definition int param[]
is adjusted; it's exactly equivalent to int *param
. And an expression of array type, in most contexts, is implicitly converted to a pointer its first element.
That's why you need to pass the size as a separate argument.
Using only C features, there are several ways to do something like returning an array:
- A function can return a pointer to the first element of a
static
array. This has some disadvantages: the size has to be fixed, and multiple callers get pointers to the same object.
- A function can receive a pointer to the first element of an array, passed in by the caller. This places the burden of allocating and deallocating the array on the caller.
- A function can return a pointer to the first element of a dynamically allocated (
malloc()
in C, new
in C++) array. This requires the caller to deallocate the array.
C++ provides a rich set of library classes that can take care of all this for you.
Recommended reading: Section 6 of the comp.lang.c FAQ.
You can pass structs as arguments, and return them as function results, and structs can contain arrays as members. But that's not as useful as you might think. An array that's a member of a struct must have a fixed size; most useful code that operates on arrays can handle dynamic sizes.