I have a corner case with regards to pointers and arrays.
How do I allocate a fixed-size (automatic) array on the heap? Let's get to the code right away to understand what I'm trying to ask:
typedef int ArrayOf10Ints[10];
int f()
{
ArrayOf10Ints * p = new ArrayOf10Ints; // Error: cannot initialize a variable of type 'ArrayOf10Ints *'
// (aka 'int (*)[10]') with an rvalue of type 'int *'
ArrayOf10Ints * q = new ArrayOf10Ints[1] // OK: allocates space for 10 ints
delete q; // Warning: use delete []
}
Why doesn't the expression to allocate p
work? Why is the rvalue an int*
and not a ArrayOf10Ints*
? And why does q
work?
Note: my goal is to understand the unexpected behavior allocating p
and q
. As others have pointed out there are many straightforward ways to solve this problem. For example, in my case, I'm using a pointer to denote that the array is optional—it may or may not exist—so I would do this instead:
boost::optional<std::array<int, 10> > optional_array;