2

In this code:

int * p = new int(44);

p is allocated on the heap and the value it points to is 44; but now I can also do something like this:

p[1] = 33;

without getting an error. I always thought

int * p = new int(44);

was just another way of saying "P is allocated on the heap and points to an address containing 44" but apparently it makes p a pointer to an array of ints? is the size of this new array 44? Or is this result unusual.

trincot
  • 317,000
  • 35
  • 244
  • 286
kjh
  • 3,407
  • 8
  • 42
  • 79
  • 4
    `p[1]` is equivalent to `*(p + 1)`. You're (un)lucky it didn't crash. You might find [this question](http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a) a good read. – chris Oct 17 '12 at 00:19

3 Answers3

5

You were right: P is allocated on the heap and points to an address containing 44. There's no array allocated. p[1] = 33; is what they call "undefined behavior". Your program might crash, but it's not guaranteed to crash every single time you do this.

Tom W
  • 1,304
  • 8
  • 9
  • 2
    Close. The variable "p" is allocated on the stack. However, the memory it points to (44) is allocated on the heap. – geometrian Oct 17 '12 at 00:34
0
int *p_scalar = new int(5); //allocates an integer, set to 5.

If you access p_scalar[n] (n <> 0) it may crash

0

In your example, the C++ language gives you a default implementation for the subscript operator for pointers that looks somehow similar to this:

(*Ptr)& operator[](size_t index)
{
   return *(address + index*sizeof(*Ptr));
}

This can always be overloaded and replaced for any type. Integers are not an exception, when you say:

int * pointer = alocate_int_array();
pointer[1] = 1;

You're using the compiler-augmented default implementation of that operator.

Karim Agha
  • 3,606
  • 4
  • 32
  • 48