c++ - 使用 strcpy_s 复制字符串

标签 c++ visual-c++

尝试使用 strcpy_s 复制字符串

char foo[10];  // a buffer able to hold 9 chars (plus the null)
char bar[] = "A string longer than 9 chars";
strcpy_s( foo, 10, bar );

得到断言:

Expression: (L"Buffer is too small" && 0)

不明白为什么。 foo 有 10 个字符的空间,第二个参数是 10。那么,有什么问题吗?

最佳答案

这是预期的行为

在您的文档中:

numberOfElements Size of the destination string buffer in char units for narrow and multi-byte functions, and wchar_t units for wide functions.

所以第二个参数是目标缓冲区的大小。并且函数会尝试从源中复制所有字符。

如果您想使用 *_s 函数复制尽可能多的元素,请考虑使用:

strncpy_s(foo, sizeof(foo)/sizeof(foo[0]), bar, _TRUNCATE);

关于c++ - 使用 strcpy_s 复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048524/

相关文章:

c++ - std::map 与 lambda 比较器

C++ 未定义对模板类方法的引用

c++ - 从 C++ 基类中的函数返回枚举

multithreading - Visual C++ (CLI) 线程

c++ - 取消定义已经包含的标题

c++ - “BackgroundSubtractorMOG”不是 ‘cv’ 的成员

C++ 和 mktime : 26/6/1943 and 27/6/1943 are the same day

c++ - 为什么#endif 包含在.h 页面的末尾?

c++ - 调试 "one line"方法

visual-c++ - google::protobuf::io::FileOutputStream 未定义?