Ad

Chapter - 5: Classes in C++

Can we increase or decrease the size of an array during execution


Ad
D
Sections
2
Exercises

Not exactly. We can change an array of size 5 into the size of 10, but it will create a new array and save in the old variable. But it is not possible to extend an array from 5 to 10 keeping its previous 5 values.

Look the example below

#include<iostream>
using namespace std;
int main()
{
	int *arr;
	int size = 3;

	arr = new int[size];

	arr[0] = 0;
	arr[1] = 1;
	arr[2] = 2;

	for (int i = 0; i < 3; i++)
		cout << endl << arr[i];

	size = 5;
	arr = new int[size]; // New sized array
		
	arr[3] = 3;
	arr[4] = 4;

	for (int i = 0; i < 5; i++) // Previous three value are lost
		cout << endl << arr[i];

	cout << "\n";
	return 0;
}
Ad

© 2024 Garbage Valuegarbage value logo