看到一个牛人写的技术博客,大大解决了我对C语言当中字符串的疑惑,学习后分享到这里。
原文链接(要翻墙): http://www.bogotobogo.com/cplusplus/string.php
学习结论:
- 数组不能直接赋值是因为数组名是个指向数组元素类型的 const pointer,如果企图 arrayA = arrayB;就相当于把arrayA 这个const pointer 重新赋值了!因此数组赋值不行。
- literal string such as "hello world!" 被编译器转换为存储在静态区的read only 内存区,并且其长度要比眼睛能看到的多一字节,存放的是 NUL Character '\0'. 当 这样双引号括起来的字符串常量出现在源代码中时,就相当于一个const char * 的指针,指向那个字符串。在C++规范中,对 literal string 进行改写是undefined,因此一般定义literal string是都用 const char * myString = "hello world!";
- A quoted string serves as the address of its first element.
-
string的概念: string都是以 '\0' 结束的字符串:char non_string [10] = {'n','o','n','_','s','t','r','i','n','g'};
char a_string [9] = {'a','_','s','t','r','i','n','g','\0'};
char non_string[] = 'A'
char a_string[] = "A";
- char array_1[ ] = 'A'; 和 char array_2[ ] = "A"; 的区别在于,array_1长度只有1,而array_2 长度是2,也就是说 双引号括起来的零个或多个字符都是string, 意味着编译器会在我们能看见的"A" 后面再加个 '\0' 字符,因为所有string都是以 '\0' 结束的。 经过测试,双引号里啥也没有时: "" 也是个表达式,也会产生一个值 '\0'.
补充,char a1 = ""; then sizeof(a1) 为 1;char a2[] = "\0"; then sizeof(a2) 为2,strlen(a1) 或者 strlen(a2) 结果都为0 ;
-
every variable with type char *
is being treated as a string. below shows the truth:char *pChar = 'A';printf(pChar);the printf() function will keep print until encountered a '\0' character. this may cause a overflow error! - C++ strings do not provide a special meaning for the character '\0', which is used as special character in an ordinary C-string to mark the end of the string.