问题
I was wondering which is the correct way?
_tcscpy(tchar_pointer, _tcslen(tchar_pointer), _T("Hello World"));
or
_tcscpy(tchar_pointer, _tcsclen(tchar_pointer), _T("Hello World"));
or
_tcscpy(tchar_pointer, ???, _T("Hello World"));
回答1:
the tchar pointer are coming from external, and my side has no idea how large the buffer referred by the pointer is
If this is so, then none of these do what you want.
The way all the "safe" functions work is that you tell them how big the target buffer is.
You don't know? You can't use those functions.
int buffer_size = _tcslen(xxx) * sizeof(TCHAR)
This will not work. All it will guarantee is that the string copied is not longer than whatever is already in the buffer. If the buffer has not been initialized, it will fail; if the buffer begins with a '\0'
, nothing will be copied; and so forth.
回答2:
Assuming you are using _tcscpy_s
and not _tcscpy
, the second parameter should be the actual size of the array, and not the length of the currently contained string. For example:
TCHAR dest[20];
_tcscpy_s(dest, _countof(dest), _T("Hello"));
You can even use the 2-parameter version that will not require the size parameter:
_tcscpy_s(dest, _T("Hello"));
If tchar_pointer
is actually a pointer and not an array (as implied by its name) you need to be very careful when determining what its actual capacity is. More context would be needed to suggest the right approach, but using the length of the contained string to compute the size of the buffer is almost certainly the wrong approach.
回答3:
bara's answer is very important for you, because the correct answer differs from all of the ideas you listed. But bara didn't explain to you the difference between _tcslen and _tcsclen, so I'll do that.
In a Unicode compilation, _tcslen and _tcsclen will both count the number of TCHARs in the current value of the string. Each TCHAR is one wchar_t.
In a Multibyte compilation, _tcslen will count the number of TCHARs in the current value of the string. Each TCHAR is one char. But _tcsclen will count the number of multibyte characters in the current value of the string. Each multibyte character is one or more TCHARs, each multibyte character is one or more chars. Different multibyte characters can have different lengths, depending on the code page and the individual characters.
回答4:
If tchar_pointer
is a pointer (as opposed to an array) you are supposed to know yourself how big the pointed-to buffer is. If you don't know, you cannot find out from the raw pointer, strcpy_s
doesn't help there.
来源:https://stackoverflow.com/questions/2946916/using-strcpy-s-for-tchar-pointer-microsoft-specific