C++中, 字符串处理的c style相关函数定义在头文件 <cstring>中。
对于数组, 只有字符型数组才在其尾部有‘\0’, 其他类型例如整数型不会有结束字符
strncpy()函数:
函数的prototype:
char * strncpy ( char * destination, const char * source, size_t num );
作用: 将source 内部存储的字符串的前num 个字符拷贝到 destination 指向的存储字符串的地址中。 如果source 内部的存储的c string 的含有的字符个数小于num的时候, 也就是说, 在copy 的过程中, 遇到了NULL character(即‘/0’, 还记得吗, 对于c style 的string 而言, 结尾是默认用‘\0’填充的, 以表示字符串结束的位置)destination 内部没有被填满(占用)的用‘0’ 填充, 直至完成达到num 的个数。
如果source字符串的字符的个数超过num个, 那么在复制num 个字符到destination的时候, 那么字符串destination 在复制的时候, 结尾并不会隐式的(implicitly)假如‘\0’亦signal 这个 c string 的结束位置。 于是destination shall not be considered a null terminated C string。 如果我们读取这个这种类型的c string的字符串, 将会产生溢出错误 (reading it as such would overflow)。 所以一般我们会手动的在destination的末尾加入一个‘\0’(空字符)。
返回值: 该函数返回的是destination。
注意事项:destination 和 source 不应该 overlap, 否则就是内存覆盖错误 .
举一个例子:
#include <iostream>
#include <cstring> // for c style string manipulation
using namespace std;
int main ()
{
char str1[]= "To be or not to be";
char str[] = "HE"; // 默认结尾有 '\0'
cout << sizeof(str) << endl;
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) ); //sizeof(str2)的输出为40, 即能够存储40个byte(char)
/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = '\0'; /* null character manually added */
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
strncpy(str1 + 3, str1, 6); // 出现内存覆盖问题
cout << str1 ;
return 0;
}
在code::blocks 的两个快捷键:
CTRL + SHIFT + F9: 编译当前文件(而不是当前打开的工程项目)
CTRL + F10: 运行上次成功编译后的程序
编译运行结果如下:
<pre name="code" class="cpp">#include <iostream>
using namespace std;
int main() {
char A[4] = {'A', 'B', 'V', 'D'}; // 系统不会默认加上\0
char B[4] = "ABC"; // a string
// B[4] = "ABCD" 会报错, 存不下
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
return 0;
}
运行结果为: