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

better approach to copy portion of char array than strncpy

我在 中使用 std::strncpy 将一个 char 数组的一部分复制到另一个 char 数组。似乎需要手动添加结束字符'[=12=]',才能正确终止字符串。

如下所示,如果不显式地将'[=12=]'追加到num1,char数组后面的部分可能还有其他字符。

  char buffer[] = "tag1=123456789!!!tag2=111222333!!!10=240";
  char num1[10];
  std::strncpy(num1, buffer+5, 9);  
  num1[9] = '[=10=]';

还有比这更好的方法吗?我想通过一步操作来达到这个目标。

是的,在 C 中使用 "strings" 相当冗长,不是吗!

幸运的是,C++ 并没有这么受限:

const char* in = "tag1=123456789!!!tag2=111222333!!!10=240";
std::string num1{in+5, in+15};

如果您不能使用 std::string,或者不想使用,则只需将您描述的逻辑包装到 函数 中,然后调用它功能。


As below, if not explicitly appending '[=13=]' to num1, the char array may have other characters in the later portion.

不太正确。没有"later portion"。您认为您观察到的 "later portion" 是您无权查看的其他内存部分。由于未能 null-terminate 你的 would-be C-string,你的程序有 未定义的行为 并且计算机可以做任何事情,比如回到过去和谋杀我的 great-great-grandmother。非常感谢,朋友!

那么值得注意的是,因为它是 C 库函数,所以 out-of-bounds 内存访问,如果你没有以那种方式使用那些库函数,那么你就不需要 到 null-terminate num1。仅当您稍后想将其视为 C-style 字符串时才需要这样做。如果你只是认为它是一个10字节的数组,那么一切都还可以。