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