I want to know how to dereference a void pointer through the way of typing it.
Lets just say that I malloc'd a huge bunch of memory and i can do whatever i want void* randomData = malloc ( 1000000 );
And i decide to make my own virtual 'int'
Im not sure how to do this.
*( int* ) ( randomData + 10 ) = ( int ) 323453 //323453 can be an int variable aswell
Im not sure if this is the right way to do perform a dereference.
This is an overview of what has to be done:
-The pointer has to be dereferenced
-Cast the pointer as an int pointer so we can change it like a normal 4-byte int
-Perform pointer arithmetic, so that the int can be placed anywhere we want
I hope I explained myself well, let me know if i havent...
EDIT: Forgot to mention that this is plain and pure C, no C++ involved
You can't do pointer arithmetic on a void pointer. That wouldn't make any sense, as pointer arithmetic is defined by the size of the type being pointed to.
*(((int*) randomData) + 10)
Basically, you just need to cast the void pointer to a real type before you do any arithmetic on it.
when working with arbitrary buffers it's common to store it as an unsigned char. This is because an unsigned char is a single byte which is the lowest level you'll work with.
> Lets just say that I malloc'd a huge bunch of memory and i can do whatever i want
> And i decide to make my own virtual 'int'
> Forgot to mention that this is plain and pure C, no C++ involved
Whether it is C or C++, alignment requirements have to be met.
I do not know how to get equivalent functionality in C (does it have an alignof keyword?), but this is how we could do it in C++.
I am slightly confused to the casting of the pointer...
How does pointer arithmetic work?
if i say randomData + 10
doesnt this mean that it is the pointer 'randomData' + 10 bytes after that?
Isnt there a way to use any sort of data type inside that malloc?
So if i 'reserved' 4 bytes for an int and then 20 bytes for a struct inside the data that was provided by malloc, couldnt i just return pointers from those places inside the malloc'd data, so that the program 'thinks' that its just normally allocated data?
EDIT: I just read a bit up on padding, I understand now that i cant just chuck an int variable in a random pointer ( e.g. 0x13247 )
doesnt this mean that it is the pointer 'randomData' + 10 bytes after that?
When you add to a pointer, it does not shift the pointer by bytes - it shifts it by whole increments of the type it points to. If it points to a type which is 4 bytes, then adding 3 to it will shift it by 12 bytes.