

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Array Decay in C++? How can it be prevented?
Here we will see what is Array Decay. The loss of type and dimensions of an array is called array decay. It occurs when we pass the array into a function by pointer or value. The first address is sent to the array which is a pointer. That is why, the size of array is not the original one.
Let us see one example of array decay using C++ code,
Example
#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); }
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
Now, we will see how to prevent the array decay in C++. 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.
Example
#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); }
Output
Actual size of array is: 40 New size of array by passing reference: 40
- Related Questions & Answers
- What is Array Decay in C++?
- What is no-confidence motion? When can it be held?
- What is non-enumerable property in JavaScript and how can it be created?
- What is SciPy in Python? Explain how it can be installed, and its applications?
- What is hysteresis thresholding? How can it be achieved using scikit-learn in Python?
- What is Cryogenic sleep and can it be put to practice practically?
- Is pizza healthy? If not, can it be made healthy?
- What is an array and how is it used for?
- What is SQL injection? How can you prevent it?
- What Is Doxing and How Can You Prevent It?
- What is Bloatware and how can you remove it?
- What is the meaning of “SELECT” statement in MySQL and how can it be used?
- In MySQL, what is Bit-field notation and how it can be used to write bit-field value?
- What is an array and what is it used for?
- What is colon cancer and how can we avoid it?
Advertisements