0
votes

I was wondering if theres a better way instead of casting a void pointer to uint8_t, then do arithmetic based on an offset, then cast it to uint32_t, then dereference it to get a 4byte value at that exact offset.

void * foo = malloc(1024);
uint32_t myVar;

for(int i = 0; i < 10; i++)
{
  myVar = *((uint32_t*)((uint8_t *) foo + nOffset));
  nOffset += 100;
}
1
Off-topic: i < 10 makes more sense than i> 10 here. - Ruud Helderman
For a slight improvement, use char instead of uint8_t. It's not the bit-width you're concerned with here, but the element size of the pointer. sizeof(char) is 1, by definition. - luser droog
@luserdroog Unless the data is actually characters, it's makes more sence to use uint8_t. While it will be no difference on just about all modern platforms, having it as the generic uint8_t gives some semantic hints when reading the code. - Some programmer dude
@JoachimPileborg Agree-ish. It's precisely those semantic hints that I'm worried about. It doesn't convey (to me) any actual meaning. I just stare at it and wonder why it isn't char. - luser droog
Since the code generally has undefined behavior, is it really worth belabouring which undefined behaviour looks prettiest? - Kerrek SB

1 Answers

1
votes

You would better simply stay within one "domain" of pointer arithmetic.

You should do uint32_t * foo = malloc(1024);

and then either

myVar = foo + nOffset / sizeof(*foo);
nOffset += 100;

or

myVar = foo + nOffset;
nOffset += 100 / sizeof(*foo);

for advancing by 100 bytes at each step.