When I use the new[] keyword (or new-operator), does it allocate memory contiguously?
int* arr = new int[10];
I mean, is there any guarantee, that arr[0] and arr[1] are closely placed, and I can iterate through the arr using pointer increments? If so, does this behavior save with structs and classes instead of int?
The C++ standard absolutely guarantees this.
arr[0]
through to arr[9]
are contiguous with no padding allowed between elements. Pointer arithmetic is valid in the allocated region. You are allowed to set a pointer to arr + 10
, but don't dereference it.
This applies to any class. The amount of memory allocated per element is sizeof(Y)
where Y
is the class or plain old data type.
Yes the elements are guaranteed to be located in consectuive memory (independent of their type). When you call new[]
you get an array and actually the only way to access the elements is via pointer arithmetics.
Consider what arr[i]
actually means:
arr[i]
is really just a short form of
*( ( arr ) + (i) )
A quirky sideeffect of this, is that for an array arr
and an index i
i[arr]
is exactly the same as arr[i]
(though you would only write this if you want to confuse your coworkers).
However, note that []
can be overloaded and in that case it can do whatever the implementation chooses. Nevertheless, also an array allocated with new[]
that has an overloaded oeprator[]
will have its elements in consecutive memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With