c++ - C/C++ 指针,ptr+1 = ptr +1 byte 还是 ptr+1*sizeof(pointer_type)?

标签 c++ c pointers gcc memory-alignment

any_type *ptr = (any_type*)malloc(sizeof(any_type)*size);
my_ptr = ptr+1;
memcpy(dst, my_ptr, sizeof(any_type));

my_ptr 会指向 ptr 之后的 1 个字节,还是指向 ptr 之后的 sizeof(any_type) 字节? 对齐选项如何影响答案?有符号/无符号类型是否不同?

最佳答案

指针运算是在指针的静态类型[*]的大小上进行的,所以它会有效地添加sizeof *ptr。成员的对齐方式将作为类型的对齐方式(对象末尾的填充)考虑到对象的大小。

struct test {
   int a;
   char b;
};

如果类型是 4 字节对齐的,test 的大小将不会是 5(假设是 32 位整数)。

[*] 请注意,在 C++ 中,您可以将派生对象的地址分配给基类,但指针算法将对指针的类型进行操作,而不是实际对象:

struct base { int x; };
struct derived : base { int y; };
int main() {
   base * p = new derived[10];
   base * q = p+1;             // this does not point to the second `derived`!!!
}

关于c++ - C/C++ 指针,ptr+1 = ptr +1 byte 还是 ptr+1*sizeof(pointer_type)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786644/

相关文章:

c++ - SSL_connect() 和 SSL_accept() 调用

c++ - 如果传递给函数,则确定数组的大小

c - 使用指针算术困惑

c++ - Qt 中的 Qwizard 在窗口 8 上不显示完成和取消按钮,相同的代码在 7 上工作

c++ - QStackWidget 中的 QDockWidget

c++ - Async_read_until 限制读取的字节大小 (Boost::asio)

c - Valgrind 向 malloc 报告愚蠢的 arg,我如何找出位置?

C 数组段错误仅在特定阈值之后

python - 获取指向列表元素的指针

c++ - 用于折叠 C++ 代码的 Visual Studio 插件