c/c++之strcat函数

守給你的承諾、 提交于 2019-12-20 07:03:05

我们首先来看这样一段代码:

#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:

  1. 当数字N不大于字符串长度时, 并不会影响最后的输出结果;
  2. 当数字N大于字符串长度时,无法拼接,输出仍然为原来的字符串;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!