Why wont nothrow work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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]; // int [i] is now stored at p
  if (p == 0) // so if p(int [i] = 0 than what happens?? ////
    cout << "Error: memory could not be allocated";// ....
  else
  {
    for (n=0; n<i; n++) // starts at array value 0. increments the loop until n = [i]
    // (number of entered [] values = number of [i]
    {
      cout << "Enter number: ";
      cin >> p[n]; // enter p and n follows the for loop. so your entering int i. but
      // i[n] would be like saying 6[9] because theyre both non pointer integers.
      // so p points to [n] and functions like a variable would for a normal array
      // like so : x[5]
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ","; /* enter p and n follows the for loop. (keep entering
p(integer i) until the n loop ends)*/

  }
     delete[]p; // not sure exactly why im using this....
    return 0; 
}





excuse the notes i took.

Why wont nothrow do anything when i enter an unreasonable value like 3,000,000,000,000 It just enters an infinite loop or if i set cin >> p[n] equal to 0 it just says the number you entered was : . than prompts me to exit

Am i using nothrow wrong?
Am i using nothrow wrong?
Yes, see http://www.cplusplus.com/reference/std/new/nothrow/

Why wont nothrow do anything when i enter an unreasonable value like 3,000,000,000,000
Thats basically the point of using nothrow. Using new without nothrow will throw an exception, you add nothrow if you dont want it to throw an exception.
(nothrough) does not through an exception but what it does is set the pointer to NULL so that the if(p==0) can easily see if allocation was successful.

I'm afraid i'm unable to help cos your code looks fine (i guess that makes it pointless posting but i've typed it out now so what the hell)
3000000000000 is probably more than int can store. Add some error checking to see that cin >> i; succeed. Change the type of i and n to a type that is big enough to represent the maximum size of any object, like std::size_t.
Last edited on
Topic archived. No new replies allowed.