Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert into void*

how can I convert any object of my own class convert into pointer to void?

MyClass obj;
(void*)obj; // Fail
like image 832
Max Frai Avatar asked Jun 30 '11 11:06

Max Frai


People also ask

What is void * in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

What does void * func () mean?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

What is void * ptr C++?

void pointer in C / C++ A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.

Can you cast anything to void *?

Any type of pointer can be assigned to (or compared with) a void pointer, without casting the pointer explicitly. Finally, a function call can be cast to void in order to explicitly discard a return value. For example, printf returns a value, but it is seldom used.


2 Answers

MyClass obj;
void *p;

p = (void*)&obj; // Explicit cast.
// or:
p = &obj; // Implicit cast, as every pointer is compatible with void *

But beware ! obj is allocated on the stack this way, as soon as you leave the function the pointer becomes invalid.

Edit: Updated to show that in this case an explicit cast is not necessary since every pointer is compatible with a void pointer.

like image 163
DarkDust Avatar answered Sep 30 '22 11:09

DarkDust


You cant convert a non-pointer to void*. You need to convert the pointer to your object to void*

(void*)(&obj); //no need to cast explicitly.

that conversion is implicit

void* p = &obj; //OK
like image 30
Armen Tsirunyan Avatar answered Sep 30 '22 10:09

Armen Tsirunyan