strcpy函数与memcpy函数今日小结

strcpy函数是字符串拷贝函数

具体用法为

strcpy(destination,source)

下面是代码

#include <stdio.h>
#include <string.h>
 
int main()
{
    char dest[20];
	char src[] = "Hello world!";
	
	strcpy(dest, src);
	printf("复制后的字符串为:%s\n", dest);
 
	return 0;
}

具体注意事项

目标字符串必须有足够的空间来存储源字符串src的内容,负责可能会发生缓冲区溢出的问题在使用strcpy函数时,应确保源字符串src以'\0'结尾,负责可能会导致复制结果不正确。

当目标字符串dest和源字符串src重叠时,使用strcpy函数可能会导致未定义的行为,应避免这种情况的发生。

还有一点,复制的时候目的数组末尾会带有/0;

memcpy函数是内存块拷贝函数

具体形式

void * memcpy ( void * destination, const void * source, size_t num );

使用方法

size_t num是字节数

前两个分别是目的地,与源头的地址

代码示例

#include<stdio.h>
#include<string.h>
 
int main()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[10] = { 0 };
	//使用memcpy()函数将arr1数组的前20字节(即前5个整形)拷进arr2中
	memcpy(arr2, arr1, 20);
 
	for (int i = 0; i < 10; i++)
		printf("%d\n", arr2[i]);
 
	return 0;
}

除了整型数据的拷贝,memcpy函数还能拷贝结构体

#include <stdio.h>
#include <string.h>
 
struct STUDENT
{
	char name[20];
	int age;
}; 
 
int main()
{
	struct STUDENT person = { "Pierre de Fermat",46 };
	struct STUDENT person_copy = { 0 };
 
	/* 使用memcpy拷贝结构体: */
	memcpy(&person_copy, &person, sizeof(person));
 
	printf("person_copy: %s, %d \n", person_copy.name, person_copy.age);
 
	return 0;
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值