How to take a pointer address as command line argument in C++

Viewed 80

I have a C++ code which will take a pointer address as an argument. The code arguments are:

./main 0x7fad529d5000

Now when reading the arguments, this value will be read as a string.

How do I convert the string "0x7fad529d5000" into an address?

2 Answers

Read a hexadecimal from stdin:

uintptr_t x;
std::cin >> std::hex >> x;

Read a hexadecimal from string:

uintptr_t x;
// assuming you used argc / argv and checked argc > 1
std::istringstream sstr( argv[1] );
sstr >> std::hex >> x; 

An alternative would be x = std::stoll( argv[1] ); but there is a cast involved there that I do not quite like (assuming the width of uintptr_t).

Converting it to a pointer:

void * p = reinterpret_cast<void *>(x);

Handle that pointer value with care, because it is unlikely to be valid. (reinterpret_cast is something that should scream "danger!" at you.)

One option is to use void* as shown below:

void func( void *param )
{
    //use param here
}
int main(int argc, char *argv[])
{
    
    std::istringstream ss(argv[1]);
    long int argInt = 0;
    //convert string arg to int arg
    ss >> std::hex >> argInt;

    //call func
    func(reinterpret_cast<void *>(argInt));
}
Related