Adding an Offset to a Pointer

If I have a pointer to an object and I want to get a pointer to an object, say, 16 bytes after the pointer, how do I add a 16-byte offset to the pointer?

In addition, memory addresses on 32-bit systems look like this: 0x00000000. If I change the address, for example 0x00000001, to 0x00000002, how many bytes are missing?

+6
source share
3 answers

Pointers count bytes, so to indicate the next byte you will need to change the value of the pointer to 1. Arithmetic of the pointer, however, counts the objects that the pointer points to, and incrementing the pointer increases its value by the size of its type of pointer. If you want to point to bytes, use the char pointer, since char is size 1 by definition, and the arithmetic pointer on char pointers allows you to point to bytes:

 T * p = get_pointer(); char * cp = reinterpret_cast<char*>(p); cp += 16; 

Cast pointers to char types do not represent ping forms and are explicitly permitted by the standard. However, you should not use the resulting pointer to access any objects that are not actually located at this address.

+6
source

If I have a pointer to an object and I want to get a pointer to an object, say, 16 bytes after the pointer, how do I add a 16-byte offset to the pointer?

Passing through char* will work, but this may be considered bad practice depending on the details of your scenario:

 T *ptr = initialize_ptr(); // Do whatever initialization you need to. ptr = (T*)(((char*)ptr) + 16); 

In addition, memory addresses on 32-bit systems look like this: 0x00000000. If I change the address, for example 0x00000001, to 0x00000002, how many bytes are missing?

The difference between 2 and 1 is 1 - exactly one byte will be skipped.

+2
source

You would do this:

 char *arr = (char*)((void*) ptrToSomeObject); &arr[15] 

What happens under the hood

  • Any ptr can be converted to 'void *'
  • 'void *' can be converted to any type of ptr.
  • arr [15] == (arr + 15bytes)
0
source

Source: https://habr.com/ru/post/896020/


All Articles