I'm trying to get a messagebox to display the address of a variable by casting an int to a const CHAR*, my current dysfunctional attempt looks like this:
#include <cstdlib>
#include <iostream>
#include <windows.h>
int main()
{
int *ip;
int pointervalue = 1337;
int thatvalue = 1;
ip = &pointervalue;
thatvalue = (int)ip;
std::cout<<thatvalue<<std::endl;
MessageBox (NULL, (const char*)thatvalue, NULL, NULL);
return 0;
}
the dos box prints 2293616, the messagebox prints "9|"
If you're using C++11, you can also use to_string()
:
MessageBox (NULL, std::to_string(thatvalue).c_str(), NULL, NULL);
Your current problem is that you're just casting thatvalue
to const char*
, or in other words, taking the int
value and converting it to a pointer , not a string (C-style or otherwise). You're getting junk printed in your message box because the const char*
pointer is pointing to invalid, junk memory, and it's an unfortunate miracle it's not crashing.
try to use stringstream instead (include sstream)
int *ip;
int pointervalue = 1337;
int thatvalue = 1;
ip = &pointervalue;
stringstream ss;
ss << hex << ip;
MessageBox (NULL, ss.str().c_str(), NULL, NULL);
Simple Casting won't do this Job.
Have a Look at the itoa function: http://www.cplusplus.com/reference/cstdlib/itoa/
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
Casting to const char * does not work because then it tries to interpret the int as a pointer.
If you want to avoid streams you can use snprintf like so
char buffer[20];
snprintf(buffer,20,"%d",thatValue);
MessageBox (NULL, (const char*)buffer, NULL, NULL);
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.