虽然要实现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;
}