-
Somethings wrong...
Hey, wondered if someone could give me a bit of wisdom as to why my program compiles fine but crashes during use.
Its just a simple program with two edit controls. I enter text into edit control A and press the "submit" button and it reappears in edit control B. This works fine for string lengths up to 10 characters...why doesn't it work for longer strings?
It either stops responding, or just closes.
Code:
switch (wParam)
{
case SUBMIT:
{
LPSTR text;
DWORD nochars =GetWindowTextLength(EntryBoxA);
if (nochars != NULL)
{
GetWindowText(EntryBoxA, text,nochars+1);
SetWindowText(EntryBoxB, text); }
else
{
MessageBox(hwnd, "No Window Text Length!", "None", MB_OK | MB_ICONINFORMATION);
}
}
break;
default:
break;
}
-
You are creating a pointer to where you want the text to go, but not the actual storage space.
When you say DWORD nochars you are creating a 4 byte entity that can hold a value. When you say LPSTR text, you are creating a 4 byte pointer that points to what? Nothing!
You need to create a char array and pass that to Get/Set WindowText().
-
>>LPSTR text;<<
Allocate memory with malloc or new (and free or delete[] it after use, of course) for the string pointer before using it . Alternatively, if you know that the string will not exceed a certain length then just declare a string (TCHAR) array of that size (+1 to include '\0' ).For example, using new
Code:
TCHAR *text;
DWORD nochars =GetWindowTextLength(EntryBoxA);
if (nochars != NULL)
{
text=new TCHAR[nochars+1];
GetWindowText(EntryBoxA, text,nochars);
SetWindowText(EntryBoxB, text);
delete[] text;
}
edit: biffed by adrianxw.
-
Thanks, :)
Both answers complemented each other great, understand that part well now...And now I thought i'd append a new topic to this post:
Say i want to compare a string (eg. "read") with that which was gathered from EntryBoxA. Now i use lstrcmp() & CompareString() and they work fine for the following examples.
-"read"
-"i have read"
But whenever there is something extra after "read" it fails to identify it correctly.
eg.-"I have read Tom Clancy's books before"
I've read the programmers reference (MSDN) and understand why its happenning with lstrcmp and i think the function CompareString works in the same way, which is why both aren't doing what i want them to do.
Can anyone tell me how i would compare just a part of the string and not the whole rest of it?
-
Okay forget the above post; Have found what i want in "tchar.h" :)