Sometimes I need to increment a pointer by 8, sometimes by 4, and sometimes by any value. How can I do this operation safely so my code runs fine in Windows 10 and Unix? I have to do it this way because I am working with a block of memory that has 8-byte integers, 4-byte integers and n-byte data.
-
3Reinterpret casts the pointer to `char*` and do the increment. – Lingxi Jan 30 '16 at 19:49
-
Cast to `char` and use + or - – Hatted Rooster Jan 30 '16 at 19:49
-
So, for example, if I need to increment a pointer by 9 bytes, casting to char and issuing ++ 9 times will do the trick. Am I correct? – JORGE Jan 30 '16 at 19:57
-
You might also want to look at this: http://stackoverflow.com/q/35071200/1116364 – Daniel Jour Jan 30 '16 at 20:03
3 Answers
Sounds simple: ((char *)ptr) += 8
.

- 6,491
- 4
- 24
- 41
-
-
Yup. The compiler reserves the right to eat your cat if, in this case, `ptr` points to a 4 byte scalar `int`. And to be doubly clear, I'm **not** talking about *dereferencing* the pointer. – Bathsheba Feb 10 '16 at 14:06
You can only do pointer arithmetic safely within the context of an array.
You are allowed to point to an element one past the array (or scalar), but, the behaviour on pointing to anything else is undefined. Certainly don't attempt to dereference a pointer that is one past the array (or scalar).
In such contexts, a cast to const char*
, and subsequent pointer arithmetic is always permissible. Note that a cast to const char*
on a 4 byte scalar int
essentially gives you the ability to increment that pointer 7 times. (3 times for the int
data, and a further 4 increments for one past the end on the original scalar).
Obey these rules and your program will work with any C++ compiler on any OS.

- 231,907
- 34
- 361
- 483
The solution which Lingxi stated would do the work. Here's an example which increments the pointer by 8 bytes by typecasting to char and re-typecasting to the required data type.
int main(){
int x=3;
int *ptr=&x;
printf("%d\n", ptr);
char *p = (char*)ptr;
p+=8; //increments pointer by 8 bytes
ptr = (int *)p;
printf("%d\n",ptr);
}
The output in my system shows:
715794828
715794836
Hope this helps!

- 1,902
- 1
- 17
- 21