指针算术的空指针的类型转换

Type conversions of a void pointer for pointer arithmetics

本文关键字:空指针 类型转换 指针      更新时间:2023-10-16

使用指针算法时,会多次转换空指针的类型。

包含数据的向量来自外部源,并返回一个void指针来访问其数据。此外,步幅也是由外部物体给出的,它注意对齐要求。简而言之,并不能充分反映这两个事实。

// Example data from external source.
struct Data {
    float x;
    float y;
    Data() : x(5), y(8) {}
};
// Example vector from external source.
size_t elements = 3;
std::vector<Data> list;
list.resize(elements);
// Pointer conversions.
const void * voidPointer = list.data(); // The external object containing the vector returns a void pointer.
const uint8_t * countPointer = static_cast<const uint8_t*>(voidPointer);
// Pointer arithmetics.
unsigned stride = sizeof(Data); // The external object returning the stride heeds alignment requirements.
for (size_t counter = 0; counter < elements; ++counter, countPointer += stride) {
    const float * pointsToFloatX = reinterpret_cast<const float*>(countPointer);
    printf("%f, ", *pointsToFloatX); // Expecting something like 5.0000, 5.0000, 5.0000
}

转换为uint8_t不会影响指针指向的(float(数据,因为只有指针的类型被转换?

为什么constcountPointer上工作,但它会递增?const是否意味着指针指向的数据可能不会被更改?

为什么我必须使用reinterpret_cast<const float*>而不是static_cast<const float*>来转换循环中的countPointer

转换为uint8_t不会影响指针指向的(float(数据,因为只有指针的类型被转换?

没错。但是在投射指针时,请记住有对齐要求。另外,请注意,&list指向vector<Data>;您可以使用list.data()来获得Data*数组。

为什么constcountPointer上工作,但它会递增?const是否意味着指针指向的数据可能不会被更改?

是的。写入float * const以使指针本身恒定,或者写入const float * const以获得指向恒定数据的恒定指针。

为什么我必须使用reinterpret_cast<const float*>而不是static_cast<const float*>来转换循环内的countPointer

兼容类型可以使用static_cast进行强制转换,其他类型则使用reinterpret_cast。CCD_ 25与其它任何一个都兼容。除非你非常确定自己在做什么,否则不要使用reinterpret_cast