strncpy函数学习

  • 原型: char* strncpy(char* string1, char* string2, int n)
  • 说明:用字符串string2的前n个字符覆盖字符串string1的前n个字符,如果string1本来有数据,会被覆盖
  • 返回值类型: 返回覆盖后字符串的指针,也就是string1的指针
int main()
{
    char a[] = "123456789";
    char b[] = "abcd";
    char* p = strncpy(a, b, 2); //只复制了b中的两个字符
    cout << a << endl;
    cout << p << endl;
    cout << sizeof(a) << endl;
    return 0;
}

运行结果:
这里写图片描述

不要以为问题就结束了,没那么简单,看下面代码

int main()
{
    char a[] = "123456789";
    char b[] = "abcd";
    char c[] = "efghijklm";
    cout << "操作前:" << endl;
    cout << "a: " << a << endl << "b: " << b << endl << "c: " << c << endl << endl;

    cout << "复制b中两个字符到a " << endl;
    char* t1 = strncpy(a, b, 2);
    cout << "a: " << a << endl;
    cout << "返回值: " << t1 << endl;
    cout << "sizeof(a): " << sizeof(a) << endl;
    cout << "strlen(a): " << strlen(a) << endl << endl;

    cout << "复制c中全部字符到b" << endl;
    cout << b << endl;
    char* t2 = strncpy(b, c, strlen(c));
    cout << "b: " << b << endl << "返回值: " << t2 << endl;
    cout << "sizeof(b): " << sizeof(b) << endl;
    cout << "strlen(b): " << strlen(b) << endl;
    return 0;
}

运行结果:
这里写图片描述

  • 当复制c中字符到b中时,结果超过了预期,b的长度变成了14,但是b数组总长度只申请了5,没有出现访问越界,至少没有报错,是怎么回事?

  • 于是又有了下面的代码:

int main()
{
    char b[] = "abcd";
    char c[] = "efghijklm";
    cout << "操作前:" << endl;
    cout << "b: " << b << endl << "c: " << c << endl << endl;

    cout << "复制c中全部字符到b" << endl;
    cout << b << endl;
    char* t2 = strncpy(b, c, strlen(c));
    cout << "b: " << b << endl << "返回值: " << t2 << endl;
    cout << "sizeof(b): " << sizeof(b) << endl;
    cout << "strlen(b): " << strlen(b) << endl;
    return 0;
}

运行结果:
这里写图片描述

  • 我们看到输出了乱码,表明发生了越界
  • 因为b中最多只能容纳5个字符,包括终结符,复制时,终结符被覆盖,输出则不知道结尾,出现了越界
  • 至于没有提示错误,可能是编译器内部做了优化,本次测试用的是codeblock

注:

使用该函数时,n的选取一定 不要超过string1的长度范围。覆盖后不要覆盖掉终结符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值