2016-07-14 19 views
-1

什麼意思是msdn中TCHAR的大小?TCHAR中的大小是sizeof或_tcslen?

例如:

的lpFileName的對象緩衝區的大小,在TCHARS。

如果我有一個緩衝:

WCHAR buf[256]; 

所以我需要通過256或512? _tsclen(buf)或sizeof(buf)?

+1

256,_tsclen(BUF),或者可以說的sizeof(BUF)/的sizeof(TCHAR) – RbMm

+1

這是的情況下,其中[匈牙利表示法](HTTPS:// EN。 wikipedia.org/wiki/Hungarian_notation)很有幫助。大多數Windows API調用使用'cch'前綴來指定*字符數量*,而'cb'前綴用於*字節數量*。 *「TCHARs中的尺寸」*與*字符數*相同。換句話說:使用'_tcslen'。 – IInspectable

回答

3

sizeof總是在char s,這相當於說它總是以字節爲單位。 TCHAR s不一定是chars,所以sizeof是錯誤的答案。

使用tsclen(buf)如果你想通過在緩衝區中的字符串的長度(以TCHAR S)是正確的。如果你想傳遞緩衝區本身的長度,你可以使用sizeof(buf)/sizeof(TCHAR),或者更一般地說,使用sizeof(buf)/sizeof(buf[0])。 Windows提供了一個叫做ARRAYSIZE的宏來避免輸入這個常見的習慣用法。

你只能這樣做,如果buf實際上是緩衝區,而不是指向緩衝區(否則sizeof(buf)給你一個指針,這是不是你需要的大小)。

一些例子:

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. 
} 
+0

再次閱讀我的問題。如果我想傳遞長度,你是在說tsclen(buf)。我問:我想要傳遞什麼:字符串的長度或buf的長度。所以我需要做的事情是:tsclen(buf)或者sizeof(buf)/ sizeof(buf [0]),如果它需要「 lpFilename緩衝區的大小,在TCHAR中 」。 ??? –

+0

這是一個很好的答案,Adrian不需要再次閱讀這個問題。 –

+0

還有'_countof' - 我不確定這和'ARRAYSIZE'有什麼區別。 –

相關問題