C++ 内存分配指针问题
考虑以下代码块:C++ 内存分配指针问题,c++,loops,pointers,C++,Loops,Pointers,考虑以下代码块: Byte* b = (Byte*) var.rawBuffer(); b += sizeof (Byte) * 9; WhateverType* aptr = (WhateverType*) b; WhateverType* anotherptr = aptr; for (int i = 0; i < N; i++) { assert(*anotherptr == aptr[i]); anotherptr += sizeof (What
Byte* b = (Byte*) var.rawBuffer();
b += sizeof (Byte) * 9;
WhateverType* aptr = (WhateverType*) b;
WhateverType* anotherptr = aptr;
for (int i = 0; i < N; i++) {
assert(*anotherptr == aptr[i]);
anotherptr += sizeof (WhateverType);
}
Byte*b=(Byte*)变量rawBuffer();
b+=sizeof(字节)*9;
WhateverType*aptr=(WhateverType*)b;
WhateverType*anotherptr=aptr;
对于(int i=0;i
为什么断言有时会失败?使用
[]
运算符扫描分配的内存时,起始内存地址上的索引是否等于将指针地址增加我试图读取的数据类型的大小?问题是这一行:
anotherptr += sizeof (WhateverType);
另一个ptr
是WhateverType*
指针,而不是Byte*
指针。当对类型化指针执行算术运算时,总字节数是指针声明为的类型的偶数倍
因此,在上面的一行中,您并没有告诉编译器只按sizeof(WhateverType)
字节数递增指针,就像您所期望的那样。实际上,您告诉它按sizeof(WhateverType)
元素数增加指针,或者换句话说,按sizeof(WhateverType)*sizeof(WhateverType)
字节数增加指针
T *pointer = ...;
pointer += N;
实际上相当于以下各项:
pointer = reinterpret_cast<T*>(reinterpret_cast<byte*>(pointer) + (sizeof(T) * N));
或更简单:
anotherptr++; // or: ++anotherptr;
您确定读取的内容没有超过缓冲区的末尾吗?如何定义
什么类型的运算符==
?你能给我们一个吗?另一个ptr+=sizeof(什么类型)代码>-->应为另一个PTR+=1
。也就是说,将字节指针强制转换为WhateverType可能仍然存在对齐问题,因为指针添加不能以这种方式工作。将for
循环中的最后一行更改为simply++另一个ptr
sizeof(WhateverType)
是sizeof(a_指针)
而不是sizeof(a_字节)
。除了类型punning之外,所有结果指针可能具有不同的对齐要求,因此,只有当T
是字节对齐时,reinterpret\u cast
行才是真的。@Swift FridayPie,你说T是字节对齐的是什么意思?你能提供一些例子吗?@rudicangiotti在cppreference.com上看到
anotherptr++; // or: ++anotherptr;