本文介绍了为什么在C ++字符串通常与'\\ 0'结束的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多code样品,人们通常使用'\\ 0'创建一个新的字符数组这样的后:

In many code samples, people usually use '\0' after creating a new char array like this:

string s = "JustAString";
char* array = new char[s.size() + 1];
strncpy(array, s.c_str(), s.size());
array[s.size()] = '\0';

为什么要使用'\\ 0'在这里?

推荐答案

你的问题引用C字符串的标题。 C ++ 的std ::字符串对象比的标准C 的字符串处理方式不同。 \\使用C字符串时,0 是很重要的,而当我使用术语字符串在这里,我指的是标准C字符串

The title of your question references C strings. C++ std::string objects are handled differently than standard C strings. \0 is important when using C strings, and when I use the term string here, I'm referring to standard C strings.

\\ 0 充当C.一个字符串结束它被称为的空字符 NUL 的。它标志着code,用于处理字符串 - 标准库也是你自己的code - 将一个字符串的结尾。一个很好的例子是的strlen 返回一个字符串的长度。

\0 acts as a string terminator in C. It is known as the null character, or NUL. It signals code that processes strings - standard libraries but also your own code - where the end of a string is. A good example is strlen which returns the length of a string.

在声明常量字符串:

const char *str = "JustAString";

那么 \\ 0 自动为您追加。在其他情况下,在那里你会管理一个非字符串常量与您的阵列为例,你有时需要自己处理。对于函数strncpy ,这是在您的示例中使用的文档,是一个很好的例证:函数strncpy 在何处整个字符串被复制之前达到指定长度的空终止字符除了的情况下副本。因此,你会经常看到函数strncpy 可能冗余的空终止分配相结合。 strlcpy strcpy_s 旨在解决从忽视处理这种情况下出现的潜在问题。

then the \0 is appended automatically for you. In other cases, where you'll be managing a non-constant string as with your array example, you'll sometimes need to deal with it yourself. The docs for strncpy, which is used in your example, are a good illustration: strncpy copies over the null termination characters except in the case where the specified length is reached before the entire string is copied. Hence you'll often see strncpy combined with the possibly redundant assignment of a null terminator. strlcpy and strcpy_s were designed to address the potential problems that arise from neglecting to handle this case.

在特定示例中,数组[s.size()] ='\\ 0'; 就是这样一个冗余:因为阵列是大小 s.size()+ 1 函数strncpy 正在复制 s.size()字符,该函数将追加 \\ 0

In your particular example, array[s.size()] = '\0'; is one such redundancy: since array is of size s.size() + 1, and strncpy is copying s.size() characters, the function will append the \0.

有关标准的C字符串工具的文件将显示,当你需要小心包括这样的空终止符。不过,仔细阅读文档:与函数strncpy 细节很容易被忽视,导致潜在的缓冲区溢出

The documentation for standard C string utilities will indicate when you'll need to be careful to include such a null terminator. But read the documentation carefully: as with strncpy the details are easily overlooked, leading to potential buffer overflows.

这篇关于为什么在C ++字符串通常与'\\ 0'结束的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!