Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

referencing problem in void * pointer?

Tags:

c++

c

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?

like image 447
teacher Avatar asked Nov 25 '25 09:11

teacher


2 Answers

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.

like image 143
Jonathan Leffler Avatar answered Nov 26 '25 22:11

Jonathan Leffler


Any pointer can be converted to void*, but it is illegal to dereference a pointer to void.

like image 20
Alexandre C. Avatar answered Nov 26 '25 23:11

Alexandre C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!