Link to problem in void * pointer?

This code:

int p = 10;
void *q;
*q = 10;

Not compiling:

'=': cannot convert from 'int' to 'void *'

However, this code compiles fine:

int p = 10;
void *q;
q = &p;

What is the reason for this?

+5
source share
8 answers

A void *indicates data of an unknown type (if it is initialized, but yours is not).

You can only assign variables of a known type or through pointers of a known type.

int p = 10;
void *q = &p;

*(int *)q = 20;

if (p != 20)
    ...something has gone horribly wrong...

This converts void *to int *and then assigns a value to this dereferenced integer pointer.

+5
source

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

+4

void * , ?

, ! , , ...!

+2

- undefined.

+1

() .

10 q. . . , -, , . -, void*, .

p q. q , p.

+1

q :

q = &p;

, q (int, long, std::string, int** ..); , , :

*q = 10;

:

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

void* s.

+1

. , - , , .

In the second block of code, you assign the address of the pointer, which works fine, since you can assign any memory address void*

0
source

your pointer qdoes not point to any place in memory. therefore, you cannot assign a value to it.

0
source

All Articles