Member-only story

Array Decay in C++/C, Ways to prevent it.

Prafulla Singh
2 min readMay 31, 2018

--

array decay is the loss of type and dimensions of an array. Usually this happens, When we pass the array into function by value or pointer. As when we send an array to a function by value or pointer, we only send first address to the array which is pointer. So the size of pointer doesn’t remain original one rather it changes to one occupied by the pointer in the memory.

Example:

#include<iostream>
using namespace std;
// array by value
void arrayByValueDecay(int *pointer)
{
// Print size
cout << "size of array using array by value: ";
cout << sizeof(pointer) << endl;
}
// array by pointer
void arrayByPointerDecay(int (*pointer)[10])
{
// Print size
cout << "size of array using array by pointer: ";
cout << sizeof(pointer) << endl;
}
int main()
{
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Size of array (sizeof(Int)*10): ";
cout << sizeof(array) <<endl;
// passing array by value
arrayByValueDecay(array);
// passing array by pointer
arrayByPointerDecay(&array);
return 0;
}

Output:

Size of array (sizeof(Int)*10): 40
size of array using array by value: 8
size of array using array by pointer: 8

How to prevent:

1: Pass size of array as parameter. So one need not to calculate it.

--

--

Prafulla Singh
Prafulla Singh

Responses (1)