C语言 ——— 模拟实现strcpy函数

目录

strcpy函数功能介绍

strcpy函数的模拟实现


strcpy函数功能介绍

学习并使用strcpy函数-CSDN博客


strcpy函数的模拟实现

代码演示:

复制代码
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* destination, const char* source)
{
	assert(destination != NULL);
	assert(source != NULL);

	char* ret = destination;

	while (*destination++ = *source++);

	return ret;
}

int main()
{
	char arr1[] = "hello world";
	char arr2[20] = { 0 };
	
	printf("%s\n", my_strcpy(arr2, arr1));
	return 0;
}

代码解析:

解析:assert(destination != NULL); & assert(source != NULL);

assert 为宏,用于断言,当 assert 中的判断式为假时,也就是当 destination 或者source为空(NULL)时,程序就会直接报错,并指出 assert 报错的行数

解析:char* ret = destination;

创建 char*类型 的 指针变量ret ,用来存储 **目的地字符串(destination)**的起始位置,以便于返回

解析:while (*destination++ = *source++);

**后置++的规则:**先使用,后++

所以是 source 解引用后赋值给解引用后的 destination,再各自++

且 while循环 内是赋值表达式,赋值表达式的结果就是 source 赋值 destination 后的结果,刚好能把 source 的 '\0' 也赋值给 destination,并且结束循环

代码验证:

当 destination 或者 source 为空(NULL)时:

不接收 my_strcpy函数 的返回值:

接收 my_strcpy函数 的返回值:

my_strcpy函数 的返回值 直接作为 printf函数 的参数:

相关推荐
Escalating_xu5 小时前
【C 语言】深入理解指针(4):回调函数、qsort、void * 与泛型排序的模拟实现
java·c语言·开发语言
吠品6 小时前
GitHub 周榜拆解:决策小模型扎堆上位
c语言·开发语言·算法
小师兄吃牛肉7 小时前
C语言篇:内联函数
c语言·开发语言
白山编程大哥7 小时前
C语言篇:语法进阶
c语言·数据结构·算法
Logic1018 小时前
C语言/数据结构动态规划题解:爬楼梯(含坏台阶)——避开障碍物的路径计数
c语言·数据结构·动态规划·时间复杂度·空间复杂度·算法题·爬楼梯
山下梅子酒2258 小时前
洛谷-入门-B2081
c语言
wuminyu9 小时前
Virtual Thread重投递至ForkJoinPool任务队列过程解析
java·linux·c语言·jvm·c++
Navigator_Z9 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
iCxhust9 小时前
51单片机电力载波应用开发(七)广播通讯
c语言·开发语言·单片机·嵌入式硬件·51单片机
Hi2024021710 小时前
同一个 NMS 算子,两种语言实现:CUDA C 与 Rust 生成 LLVM IR 和 Vortex 汇编的差异
c语言·汇编·rust·gpgpu·vortex·cudac