TCHARs 中的大小是 sizeof 还是

编程入门 行业动态 更新时间:2024-10-24 10:27:42
本文介绍了TCHARs 中的大小是 sizeof 还是 _tcslen?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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 总是在 chars 中,这相当于说它总是以字节为单位.TCHAR 不一定是 chars,所以 sizeof 是错误的答案.

sizeof is always in chars, which is equivalent to saying it's always in bytes. TCHARs 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 TCHARs) 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:关键词]

本文发布于:2023-04-26 00:48:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1126859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大小   TCHARs   sizeof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!