c语言中strncat函数,函数原型以头文件

1、函数原型

#include <stdio.h>

char *strncat(char *s1, const char *s2, size_t n) //函数的返回值为指向char型的指针,形参为两个指针(函数间数组(字符串数组)的传递是以指向数组第一个元素的指针进行的)和正整数n。 
{
    char *tmp = s1;  // 将指针 tmp 初始化为指针 s1, 指向字符串数组str1第一个元素的指针 
    while(*s1) 
        s1++; //将指针s1由指向字符串数组第一个元素,移动到指向字符串数组末尾的null字符。 
    while(n--) //循环判断条件1,n--当n小于字符串数组str2的时候,复制n个字符就截断。 此种情况s1指针最终所指的为str1最后一个字符后面的字符,不一定是null。 
        if(!(*s1++ = *s2++))  // 循环判断条件2,当n大于str2的长度的时候, 指针s2指向字符串数组末尾的null字符时,循环终止。 此种情况,s1指针最终所指为*s2传递给*s1的null字符。 
            break;
    *s1 = '';  // 之所以要这么做,是应为在n < str2的情况下,s1指针指向了str1最后一个字符的后一个字符,不一定是null,因此将其赋值为null,因为字符串终止的标志是null。 
    return tmp;
}

int main(void)
{
    char str1[128] = "abcdefg";
    char str2[128] = "123456789";
    
    size_t n;
    printf("n = "); scanf("%u", &n);
    
    printf("concatenate result: %s
", strncat(str1, str2, n));
    
    return 0;
}

2、加载strncat函数的头文件,可以直接调用strncat函数。

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

int main(void)
{
    char str1[128] = "abcdefg";
    char str2[128] = "123456789";
    
    size_t n;
    printf("n = "); scanf("%u", &n);
    
    printf("concatenate result: %s
", strncat(str1, str2, n));
    
    return 0;
}

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14836481.html