Is the new [] memory allocation contiguous?

When I use the new keyword [] (or the new-operator), does it allocate memory in turn?

int* arr = new int[10]; 

I mean, is there any guarantee that arr [0] and arr [1] are close together and I can iterate through arr using pointer increments? If so, does this behavior persist using structures and classes instead of int?

+8
c ++ new-operator
source share
2 answers

The C ++ standard absolutely guarantees this.

arr[0] to arr[9] are contiguous, with no filling allowed between elements. The pointer attribute is valid in the selection. You can set the pointer to arr + 10 , but do not look for it.

This applies to any class. The amount of allocated memory for an element is sizeof(Y) , where Y is a class or a plain old data type.

+11
source share

Yes, the elements are guaranteed to be located in the communicative memory (regardless of their type). When you call new[] , you get an array, and in fact the only way to access the elements is through pointer arithmetic.

Consider what arr[i] means:

 arr[i] 

actually only a short form

 *( ( arr ) + (i) ) 

A bizarre side effect of this is that for arr array and index i

 i[arr] 

just like arr[i] (although you would only write this if you want to confuse your colleagues).

However, note that [] can be overloaded, in which case it can do whatever the implementation chooses. However, an array allocated with new[] , which has an overloaded oeprator[] , will have its elements in sequential memory.

+2
source share

All Articles