Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array to a function

Tags:

arrays

c

When we pass an array as an argument we accept it as a pointer, that is:

func(array);//In main I invoke the function array of type int and size 5

void func(int *arr)

or

void fun(int arr[])//As we know arr[] gets converted int *arr

Here the base address gets stored in arr.

But when the passed array is accepted in this manner:

void func(int arr[5])//Works fine.

Does the memory get allocated for arr[5]?

If yes, then what happens to it?

If no, why isn't the memory allocated?

like image 754
Light Avatar asked Dec 04 '25 03:12

Light


1 Answers

Does the memory gets allocated for arr[5]?

No, it doesn't.

If no,why memory is not allocated?

Because it's not necessary. The array, when passed to a function, always decays into a pointer. So, while arrays are not pointers and pointers are not arrays, in function arguments, the following pieces of code are equivalent:

T1 function(T2 *arg);
T1 function(T2 arg[]);
T1 function(T2 arg[N]);