linux - C++ clean pointer arithmetic -


whats cleanest way perform pointer arithmetic in c++? trying add n bytes address.

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

later recast , use foo differently

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

is enough? understand pointer implementation dosent guarantee pointers (char*, int*) implemented of same size. not sure if int* (should foo*) , using unsigned int math cleanest solution. also, has work on both 32 , 64 bit.

nevermind why im doing this. not unusual though. run issue anytime youre working stream (or bytepool) of data interpreted dynamically different types.

the cleanest way of doing pointer arithmetic not via numbers of bytes, typed. don’t treat int array else, offset directly:

int* next = foo + n; 

or:

int* next = &foo[n]; 

both superior casting solution.

in cases work on byte buffer, use char*, not (never!) int*. is,

char* buffer = get_the_buffer();  // pointer arithmetic uses sizeof(char) == 1 

if need increment bytewise inside non-byte array, first ask why hell doing that. then, cast char* , pointer arithmetic; not cast int or other integral types:

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

instead of char can use unsigned char arguably makes more sense represent bytes has no influence on pointer arithmetic. careful alignment however: cannot reliably access incremented pointer using original type more. strictly undefined behaviour (= bad!) access unaligned memory. in best cases it’s slow. in worst case, crashes.

it goes without saying of extremely low level. there no uses such code more. low-level libraries should prefer use c++ standard library facilities kind of code, , pointer arithmetic in particular has fewer , fewer uses.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -