The compilers for C++ may behave differently. Since an array in C++ can be declared using the following methods:
Method A:
int size;
cout << "Enter size of array: ";
cin >> size;
int x[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
Method B
int size;
cout << "Enter size of array: ";
cin >> size;
int *x = new int[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
Both are working fine by taking input from user at run-time. I know, using method B, we have to delete x
like delete [] x
.
- Why to use
int *x = new int[size];
, if both are serving the same purpose? - What is the benefit of using
new
?
Following is the code snippet I'm testing:
#include<iostream>
using namespace std;
int main()
{
int size;
cout << "Enter size of array: ";
cin >> size;
//int *x = new int[size];
int x[size];
for (int i = 0; i < size; i++)
{
//cout << "x[" << i << "] = ";
x[i] = i + 1;
}
cout << endl << "Display" << endl;
for (int i = 0; i < size; i++)
{
cout << "x[" << i << "] = " << x[i] << endl;
}
return 0;
}