Results 1 to 2 of 2

Thread: Type casting ??

  1. #1

    Thread Starter
    Addicted Member Cbomb's Avatar
    Join Date
    Jul 1999
    Posts
    153

    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!
    Cbomb
    Techie

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width