Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a void pointer called ptr. I want to increment this value by a number of bytes. Is there a way to do this?

Please note that I want to do this in-place without creating any more variables.

Could I do something like ptr = (void *)(++((char *) ptr)); ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
520 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.

You can, however, cast the pointer to a char*, do arithmetic on that pointer, and then convert it back to a void*:

void* p = /* get a pointer somehow */;

// In C++:
p = static_cast<char*>(p) + 1;

// In C:
p = (char*)p + 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...