Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between foo(int arr[]) and foo(int arr[10])?

Tags:

c

function

Is there any difference between two function in C?

void f1(int arr[]) {    
//some code...  
}
void f2(int arr[10]) {
//some code
}

What will be the size of first array in f1 function?

like image 269
Tony Stark Avatar asked Jan 27 '16 16:01

Tony Stark


2 Answers

Is there any difference between two function in c?

No difference here. Both will be interpreted as int *arr by the compiler as arrays are converted to a pointer to its first element when used as a function parameter.

what will be the size of first array in f1 function?

Strictly speaking, there is no array here. Its only pointer to an int. If you will use sizeof(arr), then you will get the value equal to sizeof(int *).

The array size in parameters are needed when the type of parameter is a pointer to an array. in this case you need to have specify the size of array as each size makes the pointer to point to different type.

void f3(int (*arr)[10]); // Expects a pointer to an array of 10 int
like image 151
haccks Avatar answered Oct 31 '22 12:10

haccks


When an array is passed to a function, it decays into a pointer to the first element of the array.

So this:

void f1(int arr[])

And this:

void f1(int arr[10])

And this:

void f1(int *arr)

Are all equivalent.

In fact if you passed int a[20] to a function declared to take int arr[10], gcc won't complain.

like image 43
dbush Avatar answered Oct 31 '22 10:10

dbush