简体   繁体   中英

How to typecast a void pointer to an int pointer and then store an int in it?

1.    void* x;
2.    x = new int [10];
3.    x = static_cast<int*>(x);
4.    *x = 2;

On line 4, I am getting: error: 'void*' is not a pointer-to-object type

You need to define the new pointer type.

You static casted x, but the type information is lost after the static cast since at declaration time x is void*.

x will persist to be void* throughout his lifetime.

Here's a working code sample :

     void* x;
     int* ptr;
     x = new int[10];
     ptr = static_cast<int*>(x);
     *ptr = 2;

OR alternativelly, you can asign and cast in the same line :

    *(static_cast<int*>(x)) = 2;

Since any pointer (except pointer to member and pointer to functions, which are something else entirely) can be implicitly converted to a void pointer, your line 2 implicitly converts the result of new int[10] from int * to void * .

Similarly, your line 3 explicitly converts x to int * (the static_cast ) and the result of that is implicitly converted back and stored in x . That has no net effect. If the compiler is smart enough, it would ignore that statement completely.

What you need to do is introduce another variable which is a pointer to int .

void *x;
x = new int[10];
int *y = static_cast<int *>(x);
*y = 2;

If you really want to use a void pointer without any variable that is an int pointer, do this;

void *x;
x = new int[10];
*(static_cast<int *>(x)) = 2;

That is exceedingly ugly, and only needed in specialised circumstances.

In practice, unless you need the void pointer for something else in particular, eliminate it completely.

int *x;
x = new int[10];
*x = 2;

The fact that there is no need to monkey around with any explicit type conversions makes this less error prone too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM