模拟实现Strncat函数

虽然要实现strncat函数比较简单,但是其中有一些细节仍需注意,此代码一些传参,指针指向应注意的细节都在代码中注释,希望读者能注意,理解这些内容,就酱…

#define _CRT_SECURE_NO_WARNINGS 

#include <stdio.h>
#include<assert.h>

char* MyStrncat(char* dest, const char* src, int num)
{
    assert(src);
    assert(dest);

    int i = 0;
    char* tmp = dest;//可以不定义第三个变量,将其此函数设置为void,但此处定义旨在在主函数调用printf里输入此函数参数,完成链式访问

    while (*dest)
    {
        dest++;//此处dest++改变的是形参指向的地址,而主函数destionation指向首元素并没有改变
    }

    while (i < num)
    {
        *(dest +i) = *(src + i);
        i++;
    }

    *(dest + i + 1) = '\0';//destination元素后都是'\0',此处加'\0'并不是多余的。因为若主函数修恰巧提前在dest+strlen(dest)+num紧后面修改了值,此处不将其置为'\0',输出的话会将连接后面的多于内容也输出

    return tmp;

}


int main()
{
    char *source = "abcdefg";
    char destination[64] = {"1234567"};
    int number = 0;//存放用户想连接的内容长度


    printf("Input a number how many you want copy...\n");
    scanf("%d", &number);


    printf("Destination bcome:");
    //printf("%s\n", destination);//可以直接输出destination改变后的结果,destination此时仍指向首元素
    printf("%s\n", MyStrncat(destination, source, number));


    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值