-
Type casting ??
This seemingly very simple thing is escaping my grasp. I want to put an INT into a messagebox (windows API) which will only take char pointer. Ok, I think: "type cast" and do the following:
Code:
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
int imyint;
char chMychar;
imyint = 20;
chMychar = (char) imyint;
MessageBox (NULL, &chMychar, "Test", MB_OK);
return (0);
}
(NOTE: That is not my exact code. Its something very very similar I just made up at school here, the real code is at my house. I'll edit it in later if it makes a differance. Oh and the compiler im using is MinGW under WindowsXP)
Ok so I complie and execute that code, and I get the message box with some weird looking ASCII contents, instead of the the number 20.
Thank you for any help you can provide!
-
It expects a pointer value. By casting 20 you've told it to print the string at that memory location which is, obviously, junk :)
To make it into a string:
Code:
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
int myint = 20;
char buf[40];
snprintf(buf, 40, "My int: %d", myint);
MessageBox(NULL, buf, "Test", MB_OK);
return 0;
}
:)