Adding an offset to a pointer

后端 未结 3 512
悲哀的现实
悲哀的现实 2020-12-03 22:56

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

Also

3条回答
  •  醉梦人生
    2020-12-03 23:33

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

    Casting 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);
    

    Also, memory addresses in 32bit systems look like this 0x00000000. If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped?

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

提交回复
热议问题