c++ - strncpy 函数不适合我正常工作

标签 c++ strncpy

我刚开始使用 C++,所以我可能在这里犯了一个愚蠢的错误。下面是我的代码以及注释中的输出。我正在使用 Xcode。

#include <iostream>
#include <string.h>

using namespace std;

 int main() {

          char myString[] = "Hello There";
          printf("%s\n", myString);

         strncpy(myString, "Over", 5); // I want this to print out "Over There"

         cout<< myString<<endl; // this prints out ONLY as "Over"

         for (int i = 0; i <11; i++){
         cout<< myString[i];
          }// I wanted to see what's going on this prints out as Over? There
          // the ? is upside down, it got added in

         cout<< endl;
         return 0;
}

最佳答案

问题

  • > strncpy(目标、源、max_len)

strncpy 被定义为将最多 max_len 个字符从 source 复制到 destination包括 如果 source 在第一个 max_len 字节中不包含空字节,则为尾随的空字节。

在你的情况下,尾随的空字节将被包括在内,并且 destination 将在 “Over” 之后直接以 null 终止,这就是你看到的原因所描述的行为。

在调用 strncpy 后,myString 将因此比较等于:

"Over\0There"

解决方案

最直接的解决方案是不从 "Over" 复制尾随的空字节,这就像指定 4 而不是 一样简单5strncpy:

strncpy(myString, "Over", 4);

关于c++ - strncpy 函数不适合我正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599766/

相关文章:

c++ - 即使在 Visual Studio 2010 中访问变量时也会出现 C2326 错误

c++ - 使用 C++ 将 ASCII 转换为 unsigned int 形式的十六进制

c - strncpy 从 **char 到 *char[] 不复制最后一个元素

c - 为什么我的 for 循环中的 strncpy 无效?

c - 使用与其他文件相同的名称命名文件

c++ - 比 strncpy 更好的复制 char 数组部分的方法

C++11 编译器生成的函数

c++ - 使用移动时不会发生复制省略

c++ - 如何在没有竞争条件的情况下将 QFutureWatcher 与 QtConcurrent::run() 一起使用

c - Strncpy 和 char **