Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void Pointer Arithmetic

Tags:

c++

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?

like image 993
aCuria Avatar asked Jul 31 '10 11:07

aCuria


People also ask

How do you use arithmetic on a void 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)

What is a void type pointer?

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.

What can't you do on a void pointer pointer arithmetic?

Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.

What are the invalid pointer arithmetic?

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.


1 Answers

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!)

like image 97
Krevan Avatar answered Oct 16 '22 19:10

Krevan