【C语言】strcat ( ) 函数的注意点和模拟实现

阅读 57

2022-04-03

1. char * strcat ( char * destination , const char * source )

2. * 源字符串必须以 '\0' 结束。
    * 目标空间必须有足够的大,能容纳下源字符串的内容。
    * 目标空间必须可修改(即不可以出现const)
    

3. 模拟实现代码

#include <stdio.h>
char* my_strcat(char*, char*);
int main()
{
	char arr1[20] = "hello";
	char arr2[] = "honey";
	printf("%s", my_strcat(arr1, arr2));
	return 0;
}

char* my_strcat(char*destination, char*source)
{
	char *start = destination;
	char *start2 = destination;
	//计算arr1中hello的长度
	int count = 0;
	while (*destination != '\0')
	{
		++count;
		destination++;
	}
	//所以此时arr2的内容要从arr1[count]处开始存放,即指针为destination处的地址,直至遇到\0

	while (*destination++ = *source++)//这样的代码可以将\0也拷贝进去
	{
		count++;
	}

	return start2;
}

精彩评论(0)

0 0 举报