0

There is a similar question here Portable and safe way to add byte offset to any pointer

but all answers are starting with ptr = (SomeType*)... which means that I have to know the type of the pointer, while I want to use this macro:

#define ptradd(ptr, delta) (size_t) ptr = (size_t) ptr + (size_t) delta
ptradd(prect, offset);

it works under VC, but fails under GCC with the error lvalue required as left operand of assignment.

How can I make it work under GCC?

Community
  • 1
  • 1
aleksazr
  • 89
  • 7

2 Answers2

1

You are probably wrong in defining such a ptradd macro. At least, it is very bad taste (and may become undefined behavior if the pointer or the delta are not well aligned, or if the actual macro arguments have side effects like p++).

You might perhaps try (and that should usually work on most C compilers, but I don't recommend writing that)

 #define ptradd(Ptr,Delta) do{\
   Ptr=(void*)((char*)(Ptr)+(Delta));}while(0)

but I really dislike such unreadable macros. And using them e.g. as ptradd(p++,--i) is a way for disaster.

You could even replace the void* with typeof(*(Ptr))* (this is GCC specific).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

Try this.

#include <stdio.h>
#include <stdlib.h>

#define ptradd(ptr, delta) (ptr = (typeof(ptr)) ((size_t) ptr + (size_t) delta))

int main() {
    int a;
    int* b = &a;
    printf("b=%p\n", b);
    ptradd(b, 5);
    printf("b=%p\n", b);
}
Ziffusion
  • 8,779
  • 4
  • 29
  • 57