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.
Actual size of array is: 28 Modified size of array by passing by value: 8 Modified size of array by passing by pointer: 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.
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.
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- What is Memory Leak? How can we avoid?
- How can I return multiple values from a function?
- What are Wild Pointers? How can we avoid?
- What are the operators that can be and cannot be overloaded in C++?
- Can we call an undeclared function in C++?
- Can we use function on left side of an expression in C and C++?
- Can we access global variable if there is a local variable with same name?
- Can references refer to invalid location in C++?
- Can static functions be virtual in C++?
- Can a C++ class have an object of self type?
- Can namespaces be nested in C++?
- How to make a C++ class whose objects can only be dynamically allocated?
- Can we access private data members of a class without using a member or a friend function?
- Can main() be overloaded in C++?
- Can virtual functions be inlined?
- Can we use % operator on floating point numbers?
- Maximum number of threads that can be created within a process in C
- Can a constructor be private in C++ ?
- Check if a string can be formed from another string using given constraints
- Can Global Variables be dangerous ?