C/C++指针,ptr+1 = ptr+1 字节还是 ptr+1*sizeof(pointer_type)?
my_ptr会
any_type *ptr = (any_type*)malloc(sizeof(any_type)*size);
my_ptr = ptr+1;
memcpy(dst, my_ptr, sizeof(any_type));
指向 ptr 之后的 1 个字节,还是指向 ptr 之后的 sizeof(any_type) 字节? 对齐选项如何影响答案?有符号/无符号类型有什么不同吗?
Having
any_type *ptr = (any_type*)malloc(sizeof(any_type)*size);
my_ptr = ptr+1;
memcpy(dst, my_ptr, sizeof(any_type));
Will my_ptr be pointed to 1 byte after ptr, or to sizeof(any_type)
bytes after ptr?
How alignment options may affect the answer? Is it different for signed/unsigned types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
指针运算是对指针的静态类型[*]的大小进行的,因此它会有效地添加
sizeof *ptr
。成员的对齐方式将考虑到对象的大小,就像类型的对齐方式(对象末尾的填充)一样。如果类型是 4 字节对齐的话,
test
的大小将不会是 5(假设为 32 位整数)。[*] 请注意,在 C++ 中,您可以将派生对象的地址分配给基类,但指针算术将在指针的类型上进行操作,而不是实际的对象:
Pointer arithmetic is performed on the size of the static type[*] of the pointer, so it will effectively add
sizeof *ptr
. Alignment of the members will be accounted for in the size of the object, as the alignment of the type (padding at the end of the object).The size of
test
will not be 5 (assuming 32 bit ints), if the type is 4-byte aligned.[*] Note that in C++ you can assign the address of a derived object to a base class, but pointer arithmetic will operate on the type of the pointer, not the actual objects:
编译器会将 1 替换为适当的字节数。您所要做的就是指定要移动到的对象数量。
The compiler will substitute that 1 to the appropriate number of bytes. All you have to do is to specify the number of objects you want to move to.
当您看到指针时,请尝试忘记它有一个标量值。相反,可以认为指针是一种令牌,可以让您访问存储在连续空间(内存)中的对象。如果
ptr
是一个指针,可以让您访问某个(任意)位置的对象,则ptr+1
和ptr-1
将返回指针使您可以访问其邻居。When you see a pointer, try to forget that it has a scalar value. Think, instead, that the pointer is sort of a token that gives you access to an object that is stored in a continuous space (the memory). If
ptr
is a pointer that gives you access to an object at some (arbitrary) position,ptr+1
andptr-1
will return pointers that give you access to its neighbors.为了使指针算术起作用,它必须指向 sizeof(any_type) + 基地址。
For pointer arithmetic to work it has to be pointed at sizeof(any_type) + the base address.