I am using a library which has callback function with void* as a parameter. I need to get int from this void*, below code works fine in c but not in c++
In c:
void *ptr;
int n = (int)ptr;
So in c++ i tried below
int n = atoi(static_cast<const char*>(ptr));
This crashes when i run. Please help me with the right way to convert void* to int in c++
#include <iostream>
int main()
{
int x = 42;
void* p = &x; // p points to x
int y = *static_cast<int*>(p); // dereference pointer
std::cout << y << '\n';
}
That will obviously crash, if p does not point to an int.