String type conversion problem

In the code
1
2
3
4
5
6
7
if (LOWORD(wParam) == IDOK) //the ok button was clicked
		{
		HWND hTextForm = GetDlgItem(hDlg, IDC_TEXTFORM); //assign the editbox variable the handle of control
		LPTSTR input;
	    LPTSTR* pInput = &input;
		GetWindowText(hTextForm, (LPWSTR)pInput, 100); 
		MessageBox(hDlg, input, L"TITLE", MB_OK);


I am trying to display in a message box, the value the user typed into the text control IDC_TEXTFORM

the program crashes. I think it has something to do with me trying to conver pInput to LPWSTR so that MessageBox will accept it as the caption string value.

HELP!!?
LPTSTR is a pointer, not a string. Your code is corrupting the heap. Hence the crash.

1
2
3
TCHAR input[100];
GetWindowText(hTextForm,input,100);  // no need to cast here
MessageBox(hDlg, input, _T("TITLE"), MB_OK);  // use _T() instead of L 
Ah, thanks I figured it out. I thought that the pointer argument had to be an actual pointer variable to a char, but all I had to do was initiate a char variable with char myChar[] = {0} and then use myChar as the argument. I would like to know exactly why myChar[] = {0} works, though. And I thought that the null-terminator was a /0, not just 0?
Random tidbits of knowledge:


If you have an array partially initialized, all other elements are initialized to zero.

IE:
1
2
3
int foo[5] = {1};
// is the same as:
int foo[5] = {1,0,0,0,0};

---------------------------


Leaving the brakets empty tells the compiler to figure out the size based on the number of initializers, so:
1
2
3
char foo[] = {0};
// is the same as:
char foo[1] = {0};


----------------------------

In a string or character, the \ character is used to input an escape sequence. If the escape sequence is a number, it is treated as an octal representation of the character. If it's followed by an x then a number, it's a hex representation of a number.

IE:
1
2
3
4
5
6
7
8
9
10
11
12
13
// note that the 'A' letter is represented in ASCII as:
//  41 (hex)
//  101 (octal)
//  65 (decimal)

// therefore all of the following lines are equivilent:
char foo = 65;   // dec
char foo = 0x41; // hex
char foo = 0101; // oct

char foo = '\x41';  // hex escape
char foo = '\101';  // oct escape
char foo = 'A';  // ASCII code 


Therefore the '\0' character is just the octal escape sequence for the number 0. And therefore setting the char to 0 has the same effect.

----------------------------

You shouldn't use char strings with WinAPI if you want to be Unicode friendly. Stick with TCHAR.

See this article:

http://cplusplus.com/forum/articles/16820/
Last edited on
Topic archived. No new replies allowed.