Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ array variable in function header

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?

like image 789
John Avatar asked Oct 29 '12 23:10

John


3 Answers

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].

like image 162
Kerrek SB Avatar answered Nov 07 '22 12:11

Kerrek SB


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])
{

}
like image 35
Syntactic Fructose Avatar answered Nov 07 '22 13:11

Syntactic Fructose


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.

like image 3
Paul George Avatar answered Nov 07 '22 12:11

Paul George