Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetics after cast

Tags:

c++

c++11

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?

like image 316
bluescarni Avatar asked Mar 25 '26 19:03

bluescarni


1 Answers

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.

like image 137
Remy Lebeau Avatar answered Mar 29 '26 17:03

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!