Question

I have allocated array of void I need to acces bytes of allocated memory

void* array = (void*) malloc(12);
array[0] = 0;

It returns me this error:

main.c:9: error: invalid use of void expression
     array[0] = 0;
     ^

Is there any way how to do it ? Thanks!

Was it helpful?

Solution

Your array is a void-pointer. And void (in C) means 'has no type'. So when you dereference it (like array[0]) the compiler has no idea what that means.

To access bytes you need a char type, which is actually the C-equivalent of a byte (a remnant from the days when characters would still fit into (8-bit) bytes).

So declare your array as:

char * array = malloc(12);

Also note that you don't have to cast the result of malloc (especially in your case since it already returns a void *). And, if you want just the 12 bytes and only use them locally (within the function or translation-unit that declares it) then you can just use a 'proper array':

char array[12];

This has the added bonus that you don't need to free it afterwards.

OTHER TIPS

You need to use char or unsigned char rather than void to access the bytes:

char *array = malloc(12);
array[0] = 0;

malloc() returns a void pointer because it doesn't know the type you're allocating. You can't access the memory via that void pointer; you need to tell the compiler how to treat the block of memory. To treat it as bytes, use char or unsigned char.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top