简体   繁体   English

C / C ++中的C字符串定义

[英]C-string definition in C / C++

What really means by word "C-string" in C / C++? 在C / C ++中用“C-string”这个词真正意味着什么? Pointer to char? 指向char的指针? Array of characters? 字符数组? Or maybe const-pointer / const array of characters? 或者也许const-pointer / const数组的字符?

A "C string" is an array of characters that ends with a 0 (null character) byte. “C字符串”是以0(空字符)字节结尾的字符数组。 The array, not any pointer, is the string . 数组,而不是任何指针,是字符串 Thus, any terminal subarray of a C string is also a C string. 因此,C字符串的任何终端子阵列也是C字符串。 Pointers of type char * (or const char * , etc.) are often thought of as pointers to strings, but they're actually pointers to an element of a string, usually treated as a pointer to the initial element of a string. char * (或const char *等)类型的指针通常被认为是指向字符串的指针,但它们实际上是指向字符串元素的指针,通常被视为指向字符串初始元素的指针。

Const or non-const array of characters, terminated by a trailing 0 char. Const或非const字符数组,以尾随0 char结尾。 So all of the following are C strings: 所以以下所有都是C字符串:

char string_one[] = { 'H', 'e', 'l', 'l', 'o', 0 };
char string_two[] = "Hello"; // trailing 0 is automagically inserted by the compiler
const char *string_three = "Hello";

A C-string is a series of characters that is terminated by a 0 byte, otherwise known as a null terminated string . C字符串是一系列由0字节终止的字符,也称为空终止字符串 It can be accessed either as an array ( char[] ) or as a pointer to the first character ( char * ). 它既可以作为数组( char[] )访问,也可以作为指向第一个字符( char * )的指针访问。

In C++ there is another type of string called std::string which does not need to be terminated by a 0 byte. 在C ++中,还有另一种名为std::string ,它不需要以0字节终止。 The term C-string is often used by C++ programmers when they mean a null terminated string rather than the std::string type. C-string这个术语通常用于C ++程序员,当它们表示空终止字符串而不是std::string类型时。

根据标准(C11§7.1.1), 字符串是由第一个空字符终止并包括第一个空字符的连续字符序列, '\\0'终止的字符数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM