Array Decay in C++

In this tutorial, we will learn about array decay in C++.

Array decay occurs when there is a loss in the type or dimensions of an array. We call this as an array decay. This will occur when we pass the array to a function by value or by pointer. As we know array stores its data types as pointers, this would then send its first address to the array. Thus the size of the array is not the original one, but the size occupied by the pointer.

Code to show Array Decay

#include<bits/stdc++.h>
using namespace std;

void arrdecay(int *x)
{
    cout<<"Size of array when passed by value:";
    cout<<sizeof(x);
    cout<<endl;
}

void pointerdec(int (*x)[10])
{
    cout<<"Size of array when passed by pointer:";
    cout<<sizeof(x);
    cout<<endl;
}
int main()
{
    int nums[10] = {1,2,3,4,5,6,7,8,9,10,};
    cout<<"Size of array:";
    cout<<sizeof(nums)<<endl;
    arrdecay(nums);
    pointerdec(&nums);
    return 0;
}
Output:
Size of array:40
Size of array when passed by value:8
Size of array when passed by pointer:8

Explanation:

  1. In the code, we have defined two functions, arrdecay() and pointerdec(),which pass the array, nums, by value and by pointer respectively.
  2. The original size of the array is 40 as the data type of array nums is integer and each integer takes 4 bytes.
  3. However, when we pass the array nums by value and by pointer, the array takes its first address as a pointer and sends it as a parameter.
  4. This returns the size of the pointer occupied in the memory.
  5. So, the size of the array we get when returned by value or pointer is 8 and not 40.
  6. Thus an array decay has occurred.

How to solve Array Decay Problem in C++

Array decay problem can be solved easily by passing the array as a reference. Passing by reference would store and reflect any changes made to the actual array and also prevent the conversion of the array into a pointer. Thus, a decay can be prevented. Code is as follows:

#include<bits/stdc++.h>
using namespace std;

void refdecay(int (&x)[10])
{
    cout<<"Size of array when passed by reference:";
    cout<<sizeof(x);
    cout<<endl;
}
int main()
{
    int nums[10] = {1,2,3,4,5,6,7,8,9,10,};
    cout<<"Size of array:";
    cout<<sizeof(nums)<<endl;
    refdecay(nums);
    return 0;
}
Output:
Size of array:40
Size of array when passed by reference:40

As we can see, passing the array by reference does return the exact size of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *