Mat*_*ner 1 c c++ pointers char pointer-arithmetic
在下面的代码行中,我需要pm通过其中一个字段中的字节偏移量来调整指针.是否有更好/更简单的方法来做到这一点,除了不断铸造背面和来回char *并PartitionMap *使得指针运算仍然有效呢?
PartitionMap *pm(reinterpret_cast<PartitionMap *>(partitionMaps));
for ( ; index > 0 ; --index)
{
pm = (PartitionMap *)(((char *)pm) + pm->partitionMapLength);
}
return pm;
Run Code Online (Sandbox Code Playgroud)
对于那些无法从代码中理解的人来说,它是通过继承自的缓冲区中的可变长度描述符进行循环PartitionMap.
同样对于那些有关的人,partitionMapLength总是返回运行它的系统支持的长度.我正在遍历的数据符合UDF规范.
我经常使用这些模板:
template<typename T>
T *add_pointer(T *p, unsigned int n) {
return reinterpret_cast<T *>(reinterpret_cast<char *>(p) + n);
}
template<typename T>
const T *add_pointer(const T *p, unsigned int n) {
return reinterpret_cast<const T *>(reinterpret_cast<const char *>(p) + n);
}
Run Code Online (Sandbox Code Playgroud)
它们维护类型,但为它们添加单个字节,例如:
T *x = add_pointer(x, 1); // increments x by one byte, regardless of the type of x
Run Code Online (Sandbox Code Playgroud)