注意
以下用例为 Linux - C++11 测试结果
方法总结
- char str[6] = { ‘h’,’e’,’l’,’l’,’o’};
解释:末尾自动加 \0,即 str[5] = \0,此时数组定义的长度比字符个数多 1,即数组定义的长度是 6,而初始化列表中字符个数是 5 个
- char str[5] = { ‘h’,’e’,’l’,’l’,’o’};
解释:末尾自动加 \0,即 str[5] = \0,注意 str[5] 不在数组的定义范围内,此时数组定义的长度等于字符个数,即数组定义的长度是 5,而初始化列表中字符个数是 5 个,不推荐此种方法,可能越界操作
- char str[6] = “hello”;
解释:末尾自动加 \0,即 str[5] = \0
- char str[5] = “hello”;
解释: 编译错误,提示:const char [6] 类型的值不能用于初始化 char [5] 类型的实体
- char str[] = { ‘h’,’e’,’l’,’l’,’o’ };
解释:末尾自动加 \0,即 str[5] = \0
- char str[] = { ‘h’,’e’,’l’,’l’,’o’,’\0’};
解释:末尾自动加 \0,即 str[6] = \0,注意此时 str[5] 和 str[6] 都是 \0
- char str[] = “hello”;
解释:末尾自动加 \0,即 str[5] = \0
- char* str = “hello”;
解释:编译通过,但有告警信息:warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings];末尾自动加 \0,即 str[5] = \0;告警原因:因为 “hello” 是 const char * 型,而目标类型是 char*,不兼容
- char str = (char)”hello”;
解释:编译通过,并且无告警信息,末尾自动加 \0,即 str[5] = \0
- const char* str = “hello”;
解释:编译通过,并且无告警信息,末尾自动加 \0,即 str[5] = \0
C 语言字符串相关函数使用
1. char strcpy ( char destination, const char * source );
示例 1:
| #include
#include
using namespace std;
int main()
{
char source[] = “zhangdongyu”;
char dest[2];
memcpy(dest, source, strlen(source));
cout << dest[0] << endl;
cout << dest[1] << endl;
cout << dest << endl;
return 0;<br />}
Debug 模式:
z
h
zhangdongyu
Release 模式:
buffer overflow detected : ./main terminated
24564 Aborted (core dumped) ./main |
| —- |
示例 2:
| #include
#include
using namespace std;
void fun(char dest, char source)
{
strcpy(dest, source);
}
int main()
{
char source[] = “zhangdongyu”;
char dest[2];
fun(dest, source);
cout << dest[0] << endl;
cout << dest[1] << endl;
cout << dest << endl;
return 0;<br />}<br /><br />Debug 模式:<br />z<br />h<br />zhangdongyu
Release 模式:
buffer overflow detected : ./main terminated
24564 Aborted (core dumped) ./main |
| —- |
2. void memcpy ( void destination, const void * source, size_t num );
示例 1:
| #include
#include
using namespace std;
int main()
{
char source[] = “zhangdongyu”;
char dest[2];
memcpy(dest, source, strlen(source));
cout << dest[0] << endl;
cout << dest[1] << endl;
cout << dest << endl;
return 0;<br />}
Debug 模式:
z
h
zhangdongyu
Release 模式:
buffer overflow detected : ./main terminated
24564 Aborted (core dumped) ./main |
| —- |
示例 2:
| #include
#include
using namespace std;
void fun(char dest, char source)
{
memcpy(dest, source, strlen(source));
}
int main()
{
char source[] = “zhangdongyu”;
char dest[2];
fun(dest, source);
cout << dest[0] << endl;
cout << dest[1] << endl;
cout << dest << endl;
return 0;<br />}
Debug 模式:
z
h
zhangdongyu
Release 模式:
z
h
zhangdongyu |
| —- |
- void memmove ( void destination, const void * source, size_t num );
注意事项:现象同 memcpy 函数
其它
- 中文字符串所占的字节数与代码文件的编码方式有关。如果代码文件是 GB2312 编码(visual studio 默认编码),则一个汉字占用 2 个字节,但此时在 Linux 下用 cout 显示会乱码;如果是 UTF-8 编码则一个汉字占用 3 个字节,英文字符还是 1 个字节。例如 const char* str = “张东宇“ ,在 GB2312 编码下 strlen(str) 是 6,而在 UTF-8 编码下则是 9,用 string 对象效果一样。
