尝试使用 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/