0

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.

JORGE
  • 167
  • 1
  • 3
  • 12

3 Answers3

1

Sounds simple: ((char *)ptr) += 8.

i486
  • 6,491
  • 4
  • 24
  • 41
  • Careful. Might be UB. – Bathsheba Feb 10 '16 at 14:03
  • 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
0

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-1

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!

richik jaiswal
  • 1,902
  • 1
  • 17
  • 21