Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

int *p_scalar = new int(5); //allocates an integer, set to 5.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top