问题描述
限时送ChatGPT账号..msdn 中 TCHAR 的大小是什么意思?
What means size in TCHARs from msdn?
例如:
lpFilename 缓冲区的大小,以 TCHAR 为单位.
The size of the lpFilename buffer, in TCHARs.
如果我有一个缓冲区:
WCHAR buf[256];
所以我需要通过 256 还是 512?_tsclen(buf) 还是 sizeof(buf)?
So i need to pass 256, or 512? _tsclen(buf) or sizeof(buf)?
推荐答案
sizeof
总是在 char
s 中,这相当于说它总是以字节为单位.TCHAR
不一定是 chars
,所以 sizeof
是错误的答案.
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.
使用 tsclen(buf)
是正确的如果您想传递缓冲区中字符串的长度(以 TCHAR
为单位).如果你想传递缓冲区本身的长度,你可以使用 sizeof(buf)/sizeof(TCHAR)
或更一般地说,sizeof(buf)/sizeof(buf[0])
.Windows 提供了一个名为 ARRAYSIZE
的宏来避免输入这个常见的习惯用法.
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.
但是只有当 buf
实际上是缓冲区而不是指向缓冲区的指针(否则 sizeof(buf)
给出你是一个指针的大小,这不是你需要的).
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).
一些例子:
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.
}
这篇关于TCHARs 中的大小是 sizeof 还是 _tcslen?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论