This code:
int p = 10;
void *q;
*q = 10;
Does not compile:
'=' : cannot convert from 'int' to 'void *'
However, this code compiles fine:
int p = 10;
void *q;
q = &p;
What is the reason behind it?
A void * points to data of an unknown type (if it is initialized, which yours is not).
You can only assign to variables of a known type, or via pointers of a known type.
int p = 10;
void *q = &p;
*(int *)q = 20;
if (p != 20)
...something has gone horribly wrong...
This converts the void * into an int * and then assigns a value to that dereferenced integer pointer.
Any pointer can be converted to void*, but it is illegal to dereference a pointer to void.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With