gpt4 book ai didi

c++ - _tcsncpy_s() 覆盖旧内容?

转载 作者:行者123 更新时间:2023-11-30 03:01:49 26 4
gpt4 key购买 nike

在字符串上多次使用 _tcsncpy_s() 是否会覆盖旧内容?还是创建新内容然后指向新内容?举个简单的例子,如果我有:

    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

我在 1 处理解:我们有 myString --> 'H' 'e' 'l' 'l' 'o'

但是在第 2 点:'R' 'o' 'c' 'k' 是否被复制到 'H' 'e' 'l' 'l' 而 'o' 仍然存在?或者它现在指向内存中的一个新区域?我是否需要像 3 中那样删除并重新创建 myString?如果先复制String2再复制String1呢?有什么不同吗?还有什么可能有用的知识吗?

感谢您的宝贵时间,祝您有愉快的一天。

最佳答案

But at point 2: Does 'R' 'o' 'c' 'k' get copied over 'H' 'e' 'l' 'l', while 'o' remains?

是的。阅读 documentation :

These functions try to copy the first D characters of strSource to strDest, where D is the lesser of count and the length of strSource. If those D characters will fit within strDest (whose size is given as numberOfElements) and still leave room for a null terminator, then those characters are copied and a terminating null is appended; otherwise, strDest[0] is set to the null character and the invalid parameter handler is invoked, as described in Parameter Validation.

现在,对于您的其他问题:

Or is it now pointing to a new area in memory?

不,mystring 仍然引用同一个数组。

Do I need to delete and recreate myString like in 3?

也许吧。取决于你想做什么。如果您想要两个字符串的拷贝,那么是的,您将需要两个字符数组(静态或动态)。

What if I have copiedString2 first and then copiedString1?

在这种情况下,您会得到 Rock 作为您的字符串。

Does anything different happen?

操作后 mystring 中出现了一个不同的字符串,所以是的。

Anything else that might be useful to know?

你想连接这两个字符串吗?如果是这样,请使用连接函数,例如 strcat。另外,请注意以下划线开头的函数是非标准的、特定于供应商的函数,因此很可能无法移植。尝试使用标准定义的函数(例如strncpystrcatstrncat 等)。

MS 世界中的 _t 前缀函数通常是宏,根据您的项目设置(即是否 UNICODE/_UNICODE 预处理器宏是否已定义)。

最后,字符串复制的变体和中间带有 n 的连接从源中读取最多 n 个字符。这种设计允许程序员编写安全代码(因此 prevent buffer overflows )。

哦,在我们忘记之前,如果您使用的是 C++,则应该忘记所有 C 风格的字符串操作,而只需切换到更简洁、更易于使用的 std::string (或 std::wstring 视情况而定)。字符串复制通过简单的赋值(即 = 就足够)发生,连接同样是惯用的(即 += 就足够)。查看更多the documentation .

关于c++ - _tcsncpy_s() 覆盖旧内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10726646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com