C/C++字符串,字符数组,字符指针及其相互静态拷贝与追加的安全问题解决方案(2)

前言

接上篇内容,这次会描述字符串的安全追加,建议一样,看懂代码,不要盲目调试,多debug,多查看内存

代码及其解释

#include<stdio.h>
#include<string>
#include<iostream>

using namespace std;
#define SIZE 10
/* 在使用这些函数时,应该加以封装来达到自己想要的效果 */
//dn表示dest“已分配”(可用的)的空间
//如dest[10]="abc";那么它的可用空间应该是10
char* my_strncat(char *dest,const char *source, int dn)
{
    int slen = strlen(source);
    int dxlen = dn - strlen(dest) - 1;
    if (dxlen >= slen)
    {
        return strncat(dest, source, slen);
    }
    else
    {
        return strncat(dest, source, dxlen);
    }
    return 0;
}

int main()
{
    /* 从简单入手 */
    /* C CHAR[] TO C CHAR[] */
    /* C CHAR*(指向的是常量) TO C CHAR[] */
    char cchar1[SIZE] = "abc";    //dest
    char cchar2[3] = "de";     //source1
    char cchar3[] = "fghiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";   //source2
    char *str1 = "jk";     //source3
    char *str2 = "lmnoooooooooooooooooooooooooooooooooooo";   //source4
    //my_strncat(cchar1, str2, SIZE);
    //cout << cchar1 << endl;



    /* 在c++字符串中追加字符串*/
    string cppstr1 = "123";
    string cppstr2 = "555";
    //cppstr1.append(cchar2);
    //cppstr1.append(str1);
    //cppstr1.append(cppstr2);
    //cout << cppstr1 << endl;




    /* c++字符串追加到字符数组 */
    char cchar4[SIZE] = "abcd";    //dest
    string cppstr3 = "eturns a pointer to the destination string. No return value is reserved to indicate a"; //source1
    string cppstr4 = "et";    //source2
    my_strncat(cchar4, cppstr4.c_str(), SIZE);
    cout << cchar4 << endl;


    system("pause");
    return 0;
}

小系列文章小节

一直以为字符串就那么几个函数,玩玩api就好,没想到要注意那么多,之后自己去整理相关内容,一遍遍调试,折腾了挺久的,最终觉得,要处理好字符串和字符数组,主要还是其原理上,然后根据其内存情况来编程,而不能说一步到位,必须视需求来处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值