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

Is there a difference between the two functions in C?

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

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

+5
source share
2 answers

Is there a difference between two functions in c?

There is no difference. The compiler will be interpreted as int *arr , since arrays are converted to a pointer to their first element when using a function as a parameter.

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

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

The size of the array in the parameters is necessary when the type of the parameter is a pointer to the array. in this case, you need to specify the size of the array, since each size points to a pointer to a different type.

 void f3(int (*arr)[10]); // Expects a pointer to an array of 10 int 
+6
source

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

So this is:

 void f1(int arr[]) 

And this:

 void f1(int arr[10]) 

And this:

 void f1(int *arr) 

All are equivalent.

In fact, if you passed int a[20] function declared to accept int arr[10] , gcc will not complain.

+3
source

Source: https://habr.com/ru/post/1241642/


All Articles