Ivan
Ivan

Reputation: 409

C pointers: void vs other types

Why is the following allowed in gcc :

void **p1, **p2;

p1=*p2;

but this generates an "assignment from incompatible pointer type" error?

char **p1, **p2;
p1=*p2;

Upvotes: 0

Views: 72

Answers (2)

Tuxdude
Tuxdude

Reputation: 49473

You need:

char **p1, **p2;
/* Make sure p2 has a valid value (i.e. points to a valid memory location) before the following statement */
p1=p2;

The reason it works between void** being assigned a void* is because void pointers can point to anything.

Upvotes: 0

user529758
user529758

Reputation:

Because *p2 is of type void *, which is the generic (data) pointer type. That means, you can assign any data pointer type to a pointer of type void *, and you can also assign a void * to any type of data pointer. So

(some void **) = (some void *);

is valid.

However, char ** and char * are pointers to different types and neither of them is void *, so you can't assign one to another.

Upvotes: 3

Related Questions