Search code examples
clvaluepointer-arithmetic

Is there a "nice" way to advance a pointer to a struct by one byte?


I have a pointer to a structure that I would like to move over an address range, byte-by-byte. I have an approach that's working, but it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?


Solution

  • This doesn't make much sense. If you were to increase the struct pointer by 1 byte, you would end up with a misaligned address, which would be problematic on most systems. I'll have to assume that your system is not any of the mainstream 32/64 bit CPUs (not x86, ARM, PowerPC etc) or otherwise your question makes no sense.

    To increase the address by one byte, simply do this:

    ps = (s_t*) ((uintptr_t)ps + 1);