向指针添加偏移量 [英] Adding an offset to a pointer

查看:276
本文介绍了向指针添加偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个指向一个对象的指针,并且我想得到一个指针指向一个对象,例如在指针后面16个字节如何添加16个字节偏移量到指针?

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?

此外,32位系统中的内存地址类似于0x00000000。如果我将地址改为0x00000001到0x00000002,则跳过多少字节?

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

推荐答案

指针计数字节,字节,您需要将指针的值更改1.指针算术计算指针指向的对象,递增指针的值增加其指针类型的大小。如果要指向字节,请使用 char 指针,因为 char 根据定义具有大小1, char 指针是指向字节:

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. 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:

T * p  = get_pointer();

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

cp += 16;

对于char类型的转型指针不构成类型转换,并且被标准明确允许。但是,您不能使用生成的指针访问实际上不在该地址的任何对象。

Casting pointers to and from char types does not constitute type punning and is explicitly allowed by the standard. However, you must not use the resulting pointer to access any objects that aren't actually at that address.

这篇关于向指针添加偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆