// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int [i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
Now,
why is their a bracket enclosed in variable i?
p= new (nothrow) int [i];
why are their 2 for statements and what does a for statement do exactly?
Why is it deleting []p instead of the variable p?
why is their a bracket enclosed in variable i? &
Why is it deleting []p instead of the variable p?
Dynamically Allocates an
intarray ofielements .Deletes the dynamically allocated array.
Basic Rules of dynamic allocation in C++ are:
newto dynamically allocate memory, Usedeleteto deallocate it.new []to dynamically allocate memory, Usedelete []to deallocate it.Also, note that you are using
nothrowversion of thenewoperator, it basically returns anullif some error condition and does not throw an exception, this allows the C++ code to be compatible with the legacy c code which uses null check after memory allocations(malloc returns null on failure).what does a
forstatement do exactly?A for statement is a conditional loop construct, It keeps on executing the loop untill the
conditionremains true. The basic syntax of for loop is:why are their 2 for statements?
The first
for loopin your code gets the input from the user. It takes the input foritimes.The second
for loopprints out the contents of the array.Suggest you to pick up a good C++ book and read through the basics to understand more.