Given a void
pointer, if I want to make the void
pointer point to x
bytes ahead, how will this be best done? Is there a better way than casting to a char
pointer?
Compiler knows by type cast. Given a void *x : x+1 adds one byte to x , pointer goes to byte x+1. (int*)x+1 adds sizeof(int) bytes, pointer goes to byte x + sizeof(int)
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means it points to the address of variables. It is also called the general purpose pointer.
Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.
i) Adding ,multiplying and dividing two pointers. ii) Shifting or masking pointer. iii) Addition of float or double to pointer. iv) Assignment of a pointer of one type to a pointer of another type.
Is there a better way than casting to a char pointer?
No (except having a char *
instead of a void *
to begin with, so you don't have to cast it at all).
If this is not desirable or possible, then the only way is:
ptr = static_cast<char *>(ptr) + offset;
(Note: if you are doing this sort of stuff in C++, usually there is a much better solution. Unless you are an expert and you already ruled out every other alternative, I suggest you post a new question asking if there is a better way to do what you're trying to do!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With