【C语言】模拟strcpy函数的实现
一、strcpy函数
1、通过函数实现字符串复制
#include <stdio.h>
#include <string.h>
int main()
{
char bool_new[20];
char old[] = "Hello world!";
strcpy(bool_new, old);
printf("复制后的字符串为:%s\n", bool_new);
return 0;
}

2、strcpy函数介绍

将源指向的 C 字符串复制到目标指向的数组中,包括终止 null 字符(并在该点处停止)。
为避免溢出,目标指向的数组的大小应足够长,以保证可以完全复制,并且不应在内存中与源重叠。
二、模拟实现
用指针与数组相关知识实现代码
#include <stdio.h>
char* copy(char* new, const char* old)
{
char* t = new;
while (*old != '\0')
{
*new = *old;
new++;
old++;
}
*new = '\0'; // 在新字符串的末尾添加空字符
return t;
}
int main(void)
{
char bool_new[100] = { 0 };
const char old[100] = "Hello, world!";
printf("%s", copy(bool_new, old));
return 0;
}
本文来自博客园,作者:DevKevin,转载请注明原文链接:https://www.cnblogs.com/kevinbee/p/18678300

浙公网安备 33010602011771号