简体   繁体   English

向指针添加偏移量

[英]Adding an offset to a pointer

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? 如果我有一个指向对象的指针,并且我想获得一个指向对象的指针,该对象在指针之后说16个字节,我如何将16字节偏移量添加到指针?

Also, memory addresses in 32bit systems look like this 0x00000000. 此外,32位系统中的内存地址看起来像这个0x00000000。 If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped? 如果我将0x00000001之类的地址更改为0x00000002会跳过多少字节?

Pointers count bytes, so to point at the next byte you would need to change a pointer's value by 1. Pointer arithmetic, however, counts the objects pointed to by the pointer, and incrementing a pointer increases its value by the size of its pointee type. 指针计数字节,因此要指向下一个字节,您需要将指针的值更改为1.然而,指针算法会对指针指向的对象进行计数,并且递增指针会使其值增加其指针类型的大小。 If you want to point at bytes, use a char pointer, since char has size 1 by definition, and pointer arithmetic on char pointers is lets you point at bytes: 如果要指向字节,请使用char指针,因为char大小为1,而char指针上的指针算术允许您指向字节:

T * p  = get_pointer();

char * cp = reinterpret_cast<char*>(p);

cp += 16;

Casting pointers to and from char types does not constitute type punning and is explicitly allowed by the standard. 向char类型和从char类型转换指针不构成类型惩罚,并且标准明确允许。 However, you must not use the resulting pointer to access any objects that aren't actually at that address. 但是,您不能使用生成的指针来访问实际上不在该地址的任何对象。

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? 如果我有一个指向对象的指针,并且我想获得一个指向对象的指针,该对象在指针之后说16个字节,我如何将16字节偏移量添加到指针?

Casting through char* will work, but this may be considered bad practice depending on the details of your scenario: 通过char*会起作用,但根据您的方案的详细信息,这可能被认为是不好的做法:

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. 此外,32位系统中的内存地址看起来像这个0x00000000。 If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped? 如果我将0x00000001之类的地址更改为0x00000002会跳过多少字节?

The difference between 2 and 1 is 1 -- exactly one byte would be skipped. 2和1之间的差值为1 - 将跳过恰好一个字节。

You would do this : 你会这样做:

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

Whats happening under the hood 什么东西发生在引擎盖下

  1. Any ptr can be converted to 'void*' 任何ptr都可以转换为'void *'
  2. 'void *' can be converted to any type of ptr. 'void *'可以转换为任何类型的ptr。
  3. arr[15] == (arr+15bytes) arr [15] ==(arr + 15bytes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM