What is Array Decay in C++?

C++ProgrammingServer Side Programming

The loss of type and dimensions of an array is known as array decay. It occurs when we pass the array into a function by pointer or value. First address is sent to the array which is a pointer. That is why, the size of array is not the original one.

Here is an example of array decay in C++ language,

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);
   return 0;
}

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

To prevent array decay

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.

Here is an example of preventing array decay in C++ language,

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);
   return 0;
}

Output

Actual size of array is: 40
New size of array by passing reference: 40
raja
Published on 08-Oct-2018 09:03:57

Advertisements