用于使用字节偏移进行操作的更清晰的指针算术语法

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规范.

Jim*_*uck 5

转换是唯一的方法,无论是char*或intptr_t还是其他类型,然后是最终类型.


Eva*_*ran 5

我经常使用这些模板:

    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)

  • 通常,向结构指针添加一个字节是SIGBUS错误(核心转储)的一个配方 - 至少在结构和指针必须正确对齐的机器上.这并不能阻止这些功能有用 - 但这个例子可能有些不尽如人意. (3认同)