Array Decay In C
Last Updated :
20 Oct, 2023
In C, the array decays to pointers. It means that array decay is the process in which an array gets converted to a pointer. This leads to the loss of the type and dimension of the array.
Array decay generally happens when the array is passed to the function as the parameters. As the arrays cannot be passed by value in C, they always get converted to the pointer to its first element leading to the array decay.
We can verify this using sizeof operator which returns the size of a variable.
C Program to Demonstrate Array Decay
C
#include <stdio.h>
void function1( int array[])
{
printf ( "Size of array in function1()= %d\n" ,
sizeof (array));
}
void function2( int * array)
{
printf ( "Size of array in function2() = %d\n" ,
sizeof (array));
}
int main()
{
int array[5] = { 1, 2, 3, 4, 5 };
printf ( "Original size of array %zu\n" , sizeof (array));
function1(array);
function2(array);
return 0;
}
|
Output
Original size of array 20
Size of array in function1()= 8
Size of array in function2() = 8
Explanation
As we discussed before, the array is decayed to a pointer. So, the size of the array inside the function where we passed an array by value and pointer is the size of a pointer which is 8 bytes (size of pointer may vary depends on machine).
How to Get Size of Array Inside Function in C?
We can get the size of an array inside the function even by pass by value or pointer by passing the size as an additional argument. This is a way to tackle the array decay problem.
Here is an implementation of passing size as an argument to a function:
C
#include <stdio.h>
void func( int * array, int size)
{
printf ( "Size of array inside func = %d bytes\n" , size);
}
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
int size = sizeof (array);
printf ( "Size of array in main function = %d bytes\n" ,
size);
func(array, size);
return 0;
}
|
Output
Size of array in main function = 20 bytes
Size of array inside func = 20 bytes
Explanation
When array is passed as an argument, we can pass additional argument size to get the size of an array inside the function. Here we are using pointer, so whatever modification done inside the function will affect the original array as well.
Share your thoughts in the comments
Please Login to comment...