0

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?

Jake Freelander
  • 1,471
  • 1
  • 19
  • 26

1 Answers1

3

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.

1000 Bites
  • 1,010
  • 9
  • 9
  • A macro or `inline` function may work better, depending on how often this is called. – Fiddling Bits Aug 11 '14 at 18:56
  • I'd also add that if you are pointing to some random blob of data, `char*` is probably a better type than `void*` to be using anyway. `void*` means "I don't know what I'm pointing at" -- but you do, don't you? – cdhowie Aug 11 '14 at 18:57
  • 1
    Meh, modern compilers are smart enough to inline functions without further hints. – 1000 Bites Aug 11 '14 at 18:57
  • `inline` also doesn't guarantee that a function will be inlined. It has more to do with allowing a function to be defined in multiple translation units without causing any errors during linking than it has to do with forcing the compiler to inline. – cdhowie Aug 11 '14 at 18:58
  • its used a lot but the whole thing should take less than 1ms to execute regardless – Jake Freelander Aug 11 '14 at 18:59
  • There is some overhead with function calls. – Fiddling Bits Aug 11 '14 at 19:02
  • 1
    @1000Bites: Not always. Sometimes you have to restructure your program to get something inlined. However, I don't see how this is relevant to the question. – Ed S. Aug 11 '14 at 19:03