我们首先来看这样一段代码:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char pointer[24] = "Hello,world";
cout<<"The length of pointer:"<<strlen(pointer)<<endl;
strcat(pointer, "China.");
cout<<pointer<<endl;
strcpy(pointer,"Hello,world");
strcat(pointer+3, "China.");
cout<<pointer<<endl;
strcpy(pointer,"Hello,world");
strcat(pointer+8, "China.");
cout<<pointer<<endl;
strcpy(pointer,"Hello,world");
strcat(pointer+11, "China.");
cout<<pointer<<endl;
strcpy(pointer,"Hello,world");
strcat(pointer+12, "China.");
cout<<pointer<<endl;
return 0;
}
输出结果为:
/home/m/essential/cmake-build-debug/essential
The length of pointer:11
Hello,worldChina.
Hello,worldChina.
Hello,worldChina.
Hello,worldChina.
Hello,world
Process finished with exit code 0
我们可以清晰看到pointer+N:
- 当数字N不大于字符串长度时, 并不会影响最后的输出结果;
- 当数字N大于字符串长度时,无法拼接,输出仍然为原来的字符串;
来源:CSDN
作者:M’s Friday
链接:https://blog.csdn.net/Cloud_1234_5678/article/details/103605752