Search code examples
c++cpointerscharpointer-arithmetic

Cleaner pointer arithmetic syntax for manipulation with byte offsets


In the following lines of code, I need to adjust the pointer pm by an offset in bytes in one of its fields. Is there an better/easier way to do this, than incessantly casting back and forth from char * and PartitionMap * such that the pointer arithmetic still works out?

PartitionMap *pm(reinterpret_cast<PartitionMap *>(partitionMaps));
for ( ; index > 0 ; --index)
{
    pm = (PartitionMap *)(((char *)pm) + pm->partitionMapLength);
}
return pm;

For those that can't grok from the code, it's looping through variable length descriptors in a buffer that inherit from PartitionMap.

Also for those concerned, partitionMapLength always returns lengths that are supported by the system this runs on. The data I'm traversing conforms to the UDF specification.


Solution

  • I often use these templates for this:

        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);
        }
    

    They maintain the type, but add single bytes to them, for example:

    T *x = add_pointer(x, 1); // increments x by one byte, regardless of the type of x