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!
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.