close
The Wayback Machine - https://web.archive.org/web/20240703051609/https://www.geeksforgeeks.org/what-is-array-decay-in-c-how-can-it-be-prevented/
Open In App

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

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

What is Array Decay? 
The loss of type and dimensions of an array is known as decay of an array. This generally occurs when we pass the array into function by value or pointer. What it does is, it sends first address to the array which is a pointer, hence the size of array is not the original one, but the one occupied by the pointer in the memory.

C++
// C++ code to demonstrate array decay
#include <iostream>
using namespace std;

// Driver function to show Array decay
// Passing array by value
void aDecay(int* p)
{
    // Printing size of pointer
    cout << "Modified size of array is by "
            " passing by value: ";
    cout << sizeof(p) << endl;
}

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

    // Printing original size of array
    cout << "Actual size of array is: ";
    cout << sizeof(a) << endl;

    // Passing a pointer to array
    aDecay(a);

    return 0;
}

Output
Actual size of array is: 28
Modified size of array is by  passing by value: 8


In the above code, the actual array has 7 int elements and hence has 28 size. But by calling by value and pointer, array decays into pointer and prints the size of 1 pointer i.e. 8 (4 in 32 bit).

How to prevent Array Decay? 
A typical solution to handle decay is to pass size of array also as a parameter and not use sizeof on array parameters (See this for details)
Another way to prevent array decay is to send the array into functions by reference. This prevents conversion of array into a pointer, hence prevents the decay.

C++
// C++ code to demonstrate prevention of
// decay of array
#include<iostream>
using namespace std;

// A function that prevents Array decay
// by passing array by reference
void fun(int (&p)[7])
{
    // Printing size of array
    cout << "Modified size of array by "
            "passing by reference: ";
    cout << sizeof(p) << endl;
}

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

    // Printing original size of array
    cout << "Actual size of array is: ";
    cout << sizeof(a) <<endl;

    // Calling function by reference
    fun(a);

    return 0;
}

Output
Actual size of array is: 28
Modified size of array by passing by reference: 28


In the above code, passing array by reference solves the problem of decay of array. Sizes in both cases is 28. 

We can also preserve the size of the array by passing it as a pointer to the array which have one more dimension as compared to our array

C++
// C++ code to demonstrate array decay
#include <iostream>
using namespace std;

// Function to show that array decay happens
// even if we use pointer
void pDecay(int (*p)[7])
{
    // Printing size of array
    cout << "Modified size of array by "
            "passing by pointer: ";
    cout << sizeof(p) << endl;
}

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

    // Printing original size of array
    cout << "Actual size of array is: ";
    cout << sizeof(a) << endl;

    // Passing a pointer to array
    pDecay(&a);

    return 0;
}

Output
Actual size of array is: 28
Modified size of array by passing by pointer: 8

But in this case, we will have to treat the array in the function as 2d array and to access the value stored in the array, we have to access it like this: arr[0][1], arr[0][3], .. and so on.

 



Previous Article
Next Article

Similar Reads

Array Decay In C
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 t
3 min read
Maximum array elements that can be removed along with its adjacent values to empty given array
Given an array arr[] of size N. In each operation, pick an array element X and remove all array elements in the range [X - 1, X + 1]. The task is to find the maximum number of steps required such that no coins left in the array. Examples: Input: coins [] = {5, 1, 3, 2, 6, 7, 4} Output: 4 Explanation: Picking the coin coins[1] modifies the array arr
7 min read
Check if rearranging Array elements can form a Palindrome or not
Given a positive integer array arr of size N, the task is to check if number formed, from any arrangement of array elements, form a palindrome or not. Examples: Input: arr = [1, 2, 3, 1, 2]Output: YesExplanation: The elements of a given array can be rearranged as 1, 2, 3, 2, 1. Since 12321 is a palindrome, so output will be "Yes" Input: arr = [1, 2
7 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read
What’s difference between “array” and “&amp;array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&amp;array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
How can I return multiple values from a function?
We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo
2 min read
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
Can Virtual Functions be Private in C++?
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example: C/C++ Code // C++ program to demonstrate how a // virtual function can be private #include &lt;iostream&gt; cla
3 min read
Check if a string can be formed from another string using given constraints
Given two strings S1 and S2(all characters are in lower-case). The task is to check if S2 can be formed from S1 using given constraints: 1. Characters of S2 is there in S1 if there are two 'a' in S2, then S1 should have two 'a' also. 2. If any character of S2 is not present in S1, check if the previous two ASCII characters are there in S1. e.g., if
7 min read
Practice Tags :
three90RightbarBannerImg