有
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/