Does using _tcsncpy_s() on a string multiple times write over the old contents? Or does it create new contents and then point to the new contents? As a simple example, if i have:
LPTSTR myString = new TCHAR[MAX_PATH];
LPTSTR copiedString1 = "Hello";
LPTSTR copiedString2 = "Rock";
_tcsncpy_s(myString,MAX_PATH,copiedString1,5); //1
//delete [] myString; //3
//LPTSTR myString = new TCHAR[MAX_PATH]; //3
_tcsncpy_s(myString,MAX_PATH,copiedString2,4); //2
I understand at 1: we have myString –> ‘H’ ‘e’ ‘l’ ‘l’ ‘o’
But at point 2: Does ‘R’ ‘o’ ‘c’ ‘k’ get copied over ‘H’ ‘e’ ‘l’ ‘l’, while ‘o’ remains? Or is it now pointing to a new area in memory? Do I need to delete and recreate myString like in 3? What if I have copiedString2 first and then copiedString1? Does anything different happen? Anything else that might be useful to know?
Thank you for your time and have a nice day.
Yes. Read the documentation:
Now, for your other questions:
No,
mystringis still refers to the same array.Perhaps. Depends on what you want to do. If you want copies of both strings, then yes, you will need two character arrays (either static or dynamic).
In that case, you’d get
Rockas your string.A different string is present in
mystringafter the operations, so yes.Do you want to concatenate these two strings? If so, use a concatenating function, such as
strcat. Also, note that functions beginning with an underscore are non-standard, vendor specific functions and thus will not be portable in all probability. Try to use a standard defined function (such asstrncpy,strcat,strncatetc.).The
_tprefixed functions in MS world are most often macros that switch to the appropriate ASCII/Unicode versions of the respective functions depending on your project settings (i.e. whetherUNICODE/_UNICODEpre-processor macro has been defined or not).Finally, the variations of string copy and concatenation with an
nin between reads atmostncharacters from the source. This design is allow programmers to write secure code (and thus prevent buffer overflows).Oh, and before we forget, if you’re using C++, you ought to forget all about C-style string manipulation and simply switch over to the neater, easier to use
std::string(orstd::wstringas the case maybe). String copy happens via simple assignment (i.e.=suffices) and concatenation is equally idiomatic (i.e.+=suffices). For more check the documentation.