We can pass an array as a variable in a C/C++ function header, as in
int func(int arr[]) { ... }
I'm wondering: Is it ever possible that something goes inside the []
in a variable that's passed into the function header, or is it always empty?
For any (non-reference) type T
, the function signatures R foo(T t[])
and R foo(T t[123])
(or any other number) are identical to R foo(T * t)
, and arrays are passed by passing the address of the first element.
Note that T
may itself be an array type, such as T = U[10]
.
for a one-dimensional array, it will always be empty, the brackets are another way of writing:
int fun(int * arr)
{
}
As for a two-dimensional array, you need to specify how many elements each element itself holds
int fun(int arr[][3])
{
}
int func(int arr[]) { ... } is an invalid decleration of an array passed to a function.
An array name is a pointer variable. so it is enough that we just pass the array name (which itself is a pointer )
int func(int *arr) { ... } will pass the starting address of the array to the function so that it can use the array.
if the original array needs to be kept intact, a copy of the array can be created & used within the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With