Array Decay in C++



Array decay refers to the loss of type and dimensions of an array. The array is treated as a pointer to the first element instead of the whole array in some cases, like when we pass an array to a function by pointer or value. As a result, the original array's size and type information are lost.

Due to this decay, sizeof operator no longer gives the full size of the array instead it returns the size of the pointer. It causes incorrect behavior in functions that are dependent on knowing the number of elements.

Array decay to first element

When Does an Array Decay Occur in C++?

An array decay can occur in following scenarios −

Let's understand these three scenarios in detail and how they can trigger an array decay.

Passing an Array to a Function

While passing an array to a function, the array automatically decays into a pointer. After the decay, the function does not receive the size of the array, and only receives a pointer pointing to first element of the array.

The following example demonstrates how passing an array arr to the printSize() function decays to a pointer that points to first array element.

#include <iostream>
using namespace std;

void printSize(int *arr){
   cout << "\nSize of array inside function: " 
      << sizeof(arr) << " bytes" 
      << endl;
}

int main(){
   int arr[5] = {1, 2, 3, 4, 5};

   cout << "Original Size of the array " << sizeof(arr) 
      << " bytes" << endl;
   cout << "Number of elements: " 
      << sizeof(arr) / sizeof(arr[0]) << endl;

   // Array decay occurs here
   printSize(arr);

   return 0;
}

The output of the above code is as follows. You can observe the array size before and after passing it to the function −

Original Size of the array 20 bytes
Number of elements: 5

Size of array inside function: 8 bytes

Assigning an Array to a Pointer

You can assign an array to a pointer in C++. When you assign an array to a pointer, the array automatically decays to a pointer.

Here is an example demonstrating array decay while assigning the array arr to a pointer ptr.

#include <iostream>
using namespace std;

int main() {
   int arr[5] = {10, 20, 30, 40, 50};

    
   int* ptr = arr;  // Array decay occurs here

   cout << "Accessing elements using pointer:" << endl;
   for (int i = 0; i < 5; i++) {
      cout << "*(ptr + " << i << ") = " << *(ptr + i) << endl;
   }

   cout << "Address of arr[0]: " << &arr[0] << endl;
   cout << "Value of ptr: " << ptr << endl;

   return 0;
}

The output of the above code is as follows −

Accessing elements using pointer:
*(ptr + 0) = 10
*(ptr + 1) = 20
*(ptr + 2) = 30
*(ptr + 3) = 40
*(ptr + 4) = 50
Address of arr[0]: 0x7ffd7a353890
Value of ptr: 0x7ffd7a353890

Using an Array in Pointer Arithmetic

You can use pointer arithmetic to access array elements using arithmetic operations like addition and subtraction. This leads to array decay as the array loses its size information.

In this example, we have used *(arr + 2) to access the third element of the array −

#include <iostream>
using namespace std;

int main() {
   int arr[5] = {10, 20, 30, 40, 50};

   cout << "Array elements: ";
   for (int i = 0; i < 5; i++){
      cout << arr[i] << " ";
   }
   cout << endl;

   // Size of array before decay
   cout << "Array size before decay: " << sizeof(arr) 
      << " bytes" << endl;

   // Array decay happens here
   cout << "\n3rd element using pointer arithmetic: *(arr + 2) = " 
      << *(arr + 2) << endl;

   // Size after decay
   cout << "Size of (arr + 2): " << sizeof(arr + 2) 
      << " bytes " << endl;

   return 0;
}

The output of the above code is as follows. You can observe the size of element before and after the pointer −

Array elements: 10 20 30 40 50 
Array size before decay: 20 bytes

3rd element using pointer arithmetic: *(arr + 2) = 30
Size of (arr + 2): 8 bytes

Problems Caused by Array Decay in C++

Array decay can lead to several problems in C++ programming. Some of the problems are mentioned below:

Cannot Determine Array Size Inside Function

The array is decayed into a pointer when an array is passed as a function parameter. The pointer only stores the address and has no information about the number of elements in the array, so the sizeof() function gives the size of a pointer and array size can not be determined.

In the example below, we have passed an array arr as a parameter in the function func. We have calculated the array size in the main function and the func() function. The func() function returns the size of array.

#include <iostream>
using namespace std;

void func(int arr[]) {

   // array decay occur here as arr[] was passed as a parameter
   int size = sizeof(arr) / sizeof(arr[0]); 

   cout << "Inside function:" << endl;
   cout << "sizeof(arr) = " << sizeof(arr) << " bytes (pointer)" << endl;
   cout << "sizeof(arr[0]) = " << sizeof(arr[0]) << " bytes" << endl;
   cout << "Calculated size = " << size << " (WRONG!)" << endl;
   cout << endl;
}

int main() {
   int arr[5] = {1, 2, 3, 4, 5};

   cout << "In main function:" << endl;
   cout << "sizeof(arr) = " << sizeof(arr) << " bytes" << endl;
   cout << "sizeof(arr[0]) = " << sizeof(arr[0]) << " bytes" << endl;
   int size = sizeof(arr) / sizeof(arr[0]);
   cout << "Calculated size = " << size << " (CORRECT!)" << endl;
   cout << endl;

   func(arr);

   return 0;
}

The output of the above code is as follows −

In main function:
sizeof(arr) = 20 bytes
sizeof(arr[0]) = 4 bytes
Calculated size = 5 (CORRECT!)

Inside function:
sizeof(arr) = 8 bytes (pointer)
sizeof(arr[0]) = 4 bytes
Calculated size = 2 (WRONG!)

Warnings/Errors:
main.cpp: In function 'void func(int*)':
main.cpp:7:23: warning: 'sizeof' on array function parameter 
'arr' will return size of 'int*' [-Wsizeof-array-argument]
    7 |     int size = sizeof(arr) / sizeof(arr[0]);
      |                      ~^~~~

Cannot Copy Arrays Using = Operator

You cannot use the "=" operator to copy one array to another array as the array decays into a pointer. The '=' operator copies the address but we can not reassign the array memory as it is already fixed. So, it will show an error.

Here is an example to copy one array to another array using "=" operator.

#include <iostream>
using namespace std;

int main() {
   int a[3] = {1, 2, 3};
   int b[3];

   // Array decay happens here
   // 'a' decays to a pointer to first element
   b = a; 
           
   cout << "b elements: ";
   for (int i = 0; i < 3; i++)
      cout << b[i] << " ";

   return 0;
}

The output of the above code is as follows −

Warnings/Errors:
main.cpp: In function 'int main()':
main.cpp:11:7: error: invalid array assignment
   11 |     b = a;
      |     ~~^~~

Cannot Compare Arrays Directly

Arrays can not be compared directly using comparison operators(==, !=) because when array names are used they decay to pointers. Even after arrays having same elements, it will return false as the memory address will differ and it will compare the memory address of the pointers.

Here is an example of comparing two arrays arr1 and arr2

#include <iostream>
using namespace std;

int main() {
   int arr1[5] = {1, 2, 3, 4, 5};
   int arr2[5] = {1, 2, 3, 4, 5};

   cout << "Array 1: ";
   for (int i = 0; i < 5; i++)
      cout << arr1[i] << " ";
   cout << endl;

   cout << "Array 2: ";
   for (int i = 0; i < 5; i++)
      cout << arr2[i] << " ";
   cout << endl;

   cout << "Are arr1 and arr2 same?:  ";
   if (arr1 == arr2)
      cout << "TRUE" << endl;
   else
      cout << "\nFALSE" << endl;

   cout << "\nAddress of arr1: " << arr1 << endl;
   cout << "Address of arr2: " << arr2 << endl;

   return 0;
}

The output of the above code is given below. It can be seen that both arrays have same elements but it returns false because the addresses are different −

Array 1: 1 2 3 4 5 
Array 2: 1 2 3 4 5 
Are arr1 and arr2 same?:  
FALSE

Address of arr1: 0x7ffd8d5843b0
Address of arr2: 0x7ffd8d584390

Solution of Array Decay Problem

To avoid problem of array decay, we can follow the given methods −

Passing Array Size as Separate Parameter

To avoid array decay, you can pass the array size as a parameter along with the array as the size of the array does not get lost.

In this example, we have passed the array and its size as the function parameter. Here, array decay occurs but does not cause any problem because of array size.

#include <iostream>
using namespace std;

void printArray(int arr[], int size) {
   cout << "Given array: ";
   for (int i = 0; i < size; i++){
      cout << arr[i] << " ";
   }
   cout << endl;
}

int main() {
   int arr[5] = {10, 20, 30, 40, 50};
   int size = sizeof(arr) / sizeof(arr[0]);

   // Passing both array and size
   printArray(arr, size);

   return 0;
}

The output of the above code is as follows −

Given array: 10 20 30 40 50 

Using std::array and std::vector

You can use std::array and std::vector to avoid the array decay as these are objects in C++ and not arrays, so array decay does not occur.

Below is an example of std::array and std:: vector to avoid array decay −

#include <iostream>
#include <array>
using namespace std;

void printArray(array<int, 5> arr) {
   cout << "Array size: " << arr.size() << endl;
   cout << "Elements: ";
   for (int num : arr){
      cout << num << " ";
   }
   cout << endl;
}

int main() {
   array<int, 5> stdArr = {1, 2, 3, 4, 5};
   printArray(stdArr);

   return 0;
}

The output of the above code is as follows −

Array size: 5
Elements: 1 2 3 4 5 
#include <iostream>
#include <vector>
using namespace std;

void printVector(vector<int> vec) {
   cout << "Vector size: " << vec.size() << endl;
   cout << "Elements: ";
   for(int num : vec) {
      cout << num << " ";
   }
   cout << endl;
}

int main() {
   vector<int> vec = {1, 2, 3, 4, 5};
   printVector(vec);       
    
   return 0;
}

The output of the above code is as follows −

Vector size: 5
Elements: 1 2 3 4 5 

Conclusion

An array decay in C++ refers to the loss of dimension and type of an array that occurs due to various reasons such as, when an array is passed to a function, an array assigned to a pointer, or used in pointer arithmetic. It may cause various problems that we highlighted in this chapter along with their solutions.

Advertisements