bluescarni
bluescarni

Reputation: 3997

Pointer arithmetics after cast

Consider the following C++ pseudocode:

// Pointer to contiguous memory block suitably aligned to contain
// an array of type T. Possibly obtained via std::malloc or std::aligned_storage.
void *buffer = ...;
// Now cast as T pointer.
T *ptr = static_cast<T *>(buffer);
// Do some pointer arithmetics. For instance, construct the first two
// elements of the array.
::new (ptr) T();
::new (ptr + 1) T();
// etc.

Is this legal? What does the standard say about doing pointer arithmetics after a cast? 5.7/5 of the C++11 standard talks about arithmetics on pointers to elements of an array object, but can any contiguous memory block be considered as an array?

Upvotes: 3

Views: 220

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597051

Yes, it is legal. In terms of arithmetic, ptr + 1 is effectively the same as ((uint8)ptr) + (sizeof(*ptr)*1) for any typed pointer. So yes, given any typed pointer, the memory being pointed at can be treated as a contiguous array of elements of that pointer's type, and you can use type casts to change the behavior for any given pointer-arithmetic operation.

Upvotes: 2

user405725
user405725

Reputation:

Yes, this is legal. Pointer arithmetics don't really have anything to do with type casting. All there is in it is doing math on address using increments equal to size of the underlying types. Since these operations do not dereference a pointer (read/write memory pointed by that address), it is safe to use before object(s) initialization. And yes, you can refer to contiguous memory blocks as arrays.

Upvotes: 0

Related Questions