1

I have a pointer and I would like to convert the pointer address to a string and display the address in a message box. Is there a function similar to printf() that can format a string? This does not seem to work.

#include <windows.h>
#include <stdio.h>

int WINAPI WinMain(
    HINSTANCE hThisInstance,
    HINSTANCE prevInstance,
    LPSTR lpszArgument,
    int nFunsterStil)
{
  int x = 5;
  int* ptr = &x; 

  MessageBox(NULL, printf("%p", ptr), "Pointer", MB_OK);
  return 0;    
}

Thanks for any help.

0

4 Answers 4

4

Either use sprintf (or as someone else suggested, the more safe snprintf) to first print the pointer to a buffer or even better use a stringstream to put the pointer in a string.

stringstream tmp;
tmp << ptr;
MessageBox(NULL, tmp.str().c_str(), "Pointer", MB_OK);
Sign up to request clarification or add additional context in comments.

Comments

1

Check out std::ostringstream:

#include <sstream>

std::ostringstream oss;
int a(5);
std::string b("Hello!");

oss << "This is an example! " << a << ", so I will say " << b;

// use oss.str() to return a string!

Comments

1

Looks like a conversion that Boost can do: MessageBox(NULL, boost::lexical_cast<std::string>(&x).c_str(), "Pointer", MB_OK);

Comments

0

sprintf is good, but snprintf is better

1 Comment

Or sprintf is bad, snprintf is less bad ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.