What is Array Decay in C++? How can it be prevented?


Here we will see what is Array Decay. The loss of type and dimensions of an array is called array decay. It occurs when we pass the array into a function by pointer or value. The first address is sent to the array which is a pointer. That is why, the size of array is not the original one.

Let us see one example of array decay using C++ code,

Example

 Live Demo

#include<iostream>
using namespace std;
void DisplayValue(int *p) {
   cout << "New size of array by passing the value : ";
   cout << sizeof(p) << endl;
}
void DisplayPointer(int (*p)[10]) {
   cout << "New size of array by passing the pointer : ";
   cout << sizeof(p) << endl;
}
int main() {
   int arr[10] = {1, 2, };
   cout << "Actual size of array is : ";
   cout << sizeof(arr) <<endl;
   DisplayValue(arr);
   DisplayPointer(&arr);
}

Output

Actual size of array is : 40
New size of array by passing the value : 8
New size of array by passing the pointer : 8

Now, we will see how to prevent the array decay in C++. There are two following ways to prevent the array decay.

  • Array decay is prevented by passing the size of array as a parameter and do not use sizeof() on parameters of array.
  • Pass the array into the function by reference. It prevents the conversion of array into pointer and it prevents array decay.

Example

 Live Demo

#include<iostream>
using namespace std;
void Display(int (&p)[10]) {
   cout << "New size of array by passing reference: ";
   cout << sizeof(p) << endl;
}
int main() {
   int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   cout << "Actual size of array is: ";
   cout << sizeof(arr) <<endl;
   Display(arr);
}

Output

Actual size of array is: 40
New size of array by passing reference: 40

Updated on: 17-Dec-2019

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements