teacher
teacher

Reputation: 1015

referencing problem in void * pointer?

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?

Upvotes: 3

Views: 322

Answers (6)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

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.

Upvotes: 5

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

This changes the address in memory q points to:

q = &p;

This cannot figure out the type of what q points to (int, long, std::string, int**, etc); all it knows is the location in memory:

*q = 10;

You could do:

int *iq = static_cast<int*>(q);
*iq = 10;

You may want to read more about void*s.

Upvotes: 1

BlackBear
BlackBear

Reputation: 22979

The first snippet is undefined behavior.

Upvotes: 1

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234384

The two pieces of code (try to) do different things.

The first one is trying to assign the value 10 to the object q points to. There are two problems here. First you never initialized the pointer. You need to have it point somewhere before you can change the value of what it points to. And second, you cannot dereference void* because the type is not known.

The second piece of code is assigning the address of the variable p to q. After this q will point to the object that is stored in p.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318478

You cannot dereference a void pointer. And even if you could, your code would be writing to some random memory address and probably crash.

In the second code block you are assigning the address of the pointer which works fine since you can assign any memory address to a void*

Upvotes: 0

Alexandre C.
Alexandre C.

Reputation: 56956

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

Upvotes: 4

Related Questions