ibrahim
ibrahim

Reputation: 11

Fellow C++ programmer needs some help

 // 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?

Upvotes: 0

Views: 177

Answers (3)

Alok Save
Alok Save

Reputation: 206508

why is their a bracket enclosed in variable i? &
Why is it deleting []p instead of the variable p?

 p= new (nothrow) int [i];

Dynamically Allocates an int array of i elements .

 delete []p;

Deletes the dynamically allocated array.


Basic Rules of dynamic allocation in C++ are:

  • If you use new to dynamically allocate memory, Use delete to deallocate it.
  • If you use new [] to dynamically allocate memory, Use delete [] to deallocate it.

Also, note that you are using nothrow version of the new operator, it basically returns a null if 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 for statement do exactly?

A for statement is a conditional loop construct, It keeps on executing the loop untill the condition remains true. The basic syntax of for loop is:

for(;condition;)
{ 
    //doSomething
}

why are their 2 for statements?
The first for loop in your code gets the input from the user. It takes the input for i times.

The second for loop prints out the contents of the array.


Suggest you to pick up a good C++ book and read through the basics to understand more.

Upvotes: 5

eugene_che
eugene_che

Reputation: 1997

It is just C++ syntax.

  1. new int [i] means that we want to allocate memory to store i integers.
  2. delete [] p deletes memory bind to p. If [] are omitted, compiler assumes that p points to single instance of *p type. If instruction includes [] compiler tries to remove array of elements.

Upvotes: 2

dbarnes
dbarnes

Reputation: 1833

delete[] means that you are freeing an array back to the system, the no brackets for the if statement is optional and just means that the first line will be executed if true, I think you really need to learn some basics in C++ and programing in general, get a good book or google tutorials there are a lot of good ones out there

Upvotes: 2

Related Questions