Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ clean pointer arithmetic

whats the cleanest way to perform pointer arithmetic in C++? I am trying to add n bytes to an address.

int *foo;
foo = static_cast<int*> (static_cast<unsigned int>(foo) + sizeof(T))

Later you could recast and use foo differently

char* somestr = reinterpret_cast<char*>(foo)

Is this good enough? Now I understand pointer implementation dosent guarantee all pointers (char*, int*) to be implemented of the same size. So not sure if int* (should it be foo*) and using unsigned int for math is the cleanest solution. Also, it has to work on both 32 and 64 bit.

Nevermind why Im doing this. Its not all that unusual though. You would run into this issue anytime youre working with a stream (or bytepool) of data that is interpreted dynamically into different types.

like image 871
excalibur Avatar asked Dec 12 '25 01:12

excalibur


1 Answers

The cleanest way of doing pointer arithmetic is not via numbers of bytes, but strongly typed. Don’t treat an int array as something else, just offset directly:

int* next = foo + n;

or:

int* next = &foo[n];

Both are superior to your casting solution.

In cases where you work on byte buffer, use char*, not (never!) int*. That is,

char* buffer = get_the_buffer();

// Pointer arithmetic uses sizeof(char) == 1

If you really need to increment bytewise inside a non-byte array, first ask yourself why the hell you are doing that. Then, cast to char* and do the pointer arithmetic; do not cast to int or other integral types:

char* foo_buffer = reinterpret_cast<char*>(foo);
char* whatever = foo_buffer + n;

Instead of char you can also use unsigned char which arguably makes more sense to represent bytes but has no influence on pointer arithmetic. Be careful with alignment however: you cannot reliably access the incremented pointer using the original type any more. It is strictly undefined behaviour (= bad!) to access unaligned memory. In the best cases it’s slow. In the worst case, it crashes.

It goes without saying that all of this is extremely low level. There are almost no uses for such code any more. Even low-level libraries should prefer to use C++ standard library facilities for this kind of code, and pointer arithmetic in particular has fewer and fewer uses.

like image 82
Konrad Rudolph Avatar answered Dec 14 '25 16:12

Konrad Rudolph



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!