Array Decay In C (original) (raw)
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 `
// C Code to illustrate Array Decay #include <stdio.h>
// functions with different array passing syntax 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)); }
// driver code int main() { int array[5] = { 1, 2, 3, 4, 5 };
// Size of the original array in main function
printf("Original size of array %zu\n", sizeof(array));
// Passing the array to a function1
function1(array);
// Passing the array to a function2
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 `
// C program to get size of an array inside the function #include <stdio.h>
void func(int* array, int size) {
// Print size of array directly by size argument
printf("Size of array inside func = %d bytes\n", size);
}
int main() {
// Create an one dimensional array
int array[] = { 1, 2, 3, 4, 5 };
// Get size of an array (bytes)
int size = sizeof(array);
// print size of an array in main method
printf("Size of array in main function = %d bytes\n",
size);
// Call func function
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.