What means size in TCHARs from msdn?
For example:
The size of the lpFilename buffer, in TCHARs.
If i have a buffer:
WCHAR buf[256];
So i need to pass 256, or 512? _tsclen(buf) or sizeof(buf)?
What means size in TCHARs from msdn?
For example:
The size of the lpFilename buffer, in TCHARs.
If i have a buffer:
WCHAR buf[256];
So i need to pass 256, or 512? _tsclen(buf) or sizeof(buf)?
sizeof
is always in char
s, which is equivalent to saying it's always in bytes. TCHAR
s are not necessarily chars
, so sizeof
is the wrong answer.
Using tsclen(buf)
is correct if you want to pass the length (in TCHAR
s) of the string in the buffer. If you want to pass the length of the buffer itself, you can use sizeof(buf)/sizeof(TCHAR)
or, more generally, sizeof(buf)/sizeof(buf[0])
. Windows provides a macro called ARRAYSIZE
to avoid typing out this common idiom.
But you can only do that if buf
is actually the buffer and not a pointer to a buffer (otherwise sizeof(buf)
gives you the size of a pointer, which is not what you need).
Some examples:
TCHAR buffer[MAX_PATH];
::GetWindowsDirectory(buffer, sizeof(buffer)/sizeof(buffer[0])); // OK
::GetWindowsDirectory(buffer, ARRAYSIZE(buffer)); // OK
::GetWindowsDirectory(buffer, _tcslen(buffer)); // Wrong!
::GetWindowsDirectory(buffer, sizeof(buffer)); // Wrong!
TCHAR message[64] = "Hello World!";
::TextOut(hdc, x, y, message, _tcslen(message)); // OK
::TextOut(hdc, x, y, message, sizeof(message)); // Wrong!
::TextOut(hdc, x, y, message, -1); // OK, uses feature of TextOut
void MyFunction(TCHAR *buffer) {
// This is wrong because buffer is just a pointer to the buffer, so
// sizeof(buffer) gives the size of a pointer, not the size of the buffer.
::GetWindowsDirectory(buffer, sizeof(buffer)/sizeof(buffer[0])); // Wrong!
// This is wrong because ARRAYSIZE (essentially) does what we wrote out
// in the previous example.
::GetWindowsDirectory(buffer, ARRAYSIZE(buffer)); // Wrong!
// There's no right way to do it here. You need the caller to pass in the
// size of the buffer along with the pointer. Otherwise, you don't know
// how big it actually is.
}