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函数 的参数: 

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值