greenteam greenteam - 1 month ago 9
C Question

accessing parts of memory of a void pointer

I'm using a void pointer to store and copy data into a bunch of arrays. I am trying to make it so that if an array fills up, I continue writing the remaining data into a new array.
For example, I have a 100 byte void pointer. I want to write all of it into an array. The array only has room for 50 bytes so I then want to write the remaining 50 into a different array with available space.
Is it possible to 'index' the data of the void pointer so that I don't reuse the first 50 bytes and can access the last 50 bytes?

Answer

Staying with void pointer only , no.

When you are indexing an array , let's say :

array[10]

You are dereferencing what it as this adress.

If array if of type char * then it will cause no problem , because char is a complete type. (by complete, understand that the compiler knows it representation in memory : 1 byte)

Therefore , it is possible for the compiler to know the size of each "case" and to produce the instruction giving you the 9th element (1st being *array or array[0] )

Now let's say you use a void * pointer , and you try to access the 9th element.

The compiler simply cannot know what is the size of the data pointed by it.. void is not a complete type. So it is not able to go to any index.

So using only void pointers , no it is not possible.

But you can cast your void pointer to make it a complete type.

for example :

void * destination; 
char * array = malloc(sizeof(char) * 512);
destination = array;

((char *)destination)[10] = 'n';

Is completely valid.