Hi all. I am running into a difficulty converting TCHAR to LPTSTR, or at least in converting TCHAR* to LPTSTR. I should admit that I do not know what the '*' is doing on the end of the TCHAR (see second code snippet) and have not been able to find info on this.
My problem is that the first (practice) code works, but the second (real program) code does not (see below). Any idea what I can do?
____________________________
int main()
{
LPTSTR name;
TCHAR filename[MAX_PATH]=_T("This is a string");
name=filename;
return 0;
}
_____________________________
...
int len = GetWindowTextLength(GetDlgItem(newBay, IDC_NEWNAME));
LPTSTR name;
if(len > 0)
{
TCHAR* buf;
buf = (TCHAR*)GlobalAlloc(GPTR, len + 1);
GetDlgItemText(newBay, IDC_NEWNAME, buf, len + 1);
name=*buf;
GlobalFree((HANDLE)buf);
}
dAG newBN(nodes,name);
...
______________________________
Thanks. Sorry I forgot about your article- I knew I had seen info on this stuff somewhere...
Things are still not working.
My aim is to obtain a tstring from a dialog edit control. This tstring will be the name of a data structure the user will be working with, and is used to create and identify files that store information about that particular data structure. In the code below, test[11] simulates the text being inputted into this edit control, buf is the means I a using to obtain this edit control text. I want to be able to take the information stored at buf and transfer it to name, where it will remain even after buf is long gone.
The problem with the code given is that when debugging it comes up with the error:
'HEAP[test.exe]: Heap block at 00152E60 modified at 00152E73 past requested size of b'.
(The triggered break point is at the Global Free line.)
You have the right idea. You're very close... assuming tstring is an actual string type:
typedef std::basic_string<TCHAR> tstring;
If tstring is just a pointer, then you have a bigger problem.. but I'm going to assume it's a string.
Your other problem is you're not allocating a big enough buffer. GlobalAlloc takes the size in bytes. You're giving it the size in TCHARs so you're not allocating enough space. And therefore you're overflowing the buffer causing heap corruption, which is causing all sorts of errors when you exit.
You'd have to do: (TCHAR*)GlobalAlloc(GPTR, 11 * sizeof(TCHAR));
BUT!
1) Why are you using GlobalAlloc anyway? Why not just use new[] / delete[]?
2) If tstring is a string type, why are you even bothering allocating this buffer? This code could be greatly simplified:
1 2 3 4
TCHAR test[] = _T("this is a test");
tstring name = test; // this copies the string
// done
You already have the string in a buffer, yet you're copying it to another buffer before copying it to a string. It seems really pointless.