Jake Freelander
Jake Freelander

Reputation: 1471

What is the proper way to offset a pointer?

I'm porting some gcc C code to msvc C, it has a lot of pointer offsetting done by simply adding an integer to the pointer like this:

memcpy(data+offset, uhus->elements[i], uhsize);

It seems like C in VS2013 won't allow for that though. I remember reading somewhere that adding an integer to a pointer in C offset it by i*sizeof(datatype of the pointer), wont matter for void* like in the line above but there might be some other types elsewhere and since the software is for flashing firmware, I'd rather avoid bricking my device while testing.

Currently I've replaced the additions like this:

static void* ptrOffset(void* ptr, int offset) {
    return (void*)(((int)ptr) + offset);
}
memcpy(ptrOffset(data, offset), uhus->elements[i], uhsize);

Should do the trick, no?

Upvotes: 0

Views: 2872

Answers (1)

1000 Bites
1000 Bites

Reputation: 1040

If you really want an auxiliary function for that, the proper definition would be:

void* ptrOffset(void* ptr, int offset) {
    return (char*)ptr + offset;
}

Doing pointer arithmetic on void pointers is technically not allowed. Also, casting a pointer to int will break on 64 bit platforms: you'll lose the top 32 bits of your pointer.

Upvotes: 3

Related Questions