strcpy,memcpy和memset的用法

1,的的strcpy的用法,把一个字符串的内容拷贝给另一个字符串。

函数的原型如下

_CRTIMP char * __cdecl strcpy(char * dest,const char * src);

把SRC字符串的内容赋值给DEST,当然DEST要有足够的空间能放得下SRC拷贝过来的字符串,拷贝的过程中的src遇到'\ 0'字符串就停止了。

#include <stdio.h>
#include <string.h>

int main(void){ 
	char dest [30]; 
	char * src =“123456789”; 

	strcpy(DEST,SRC); 
	

	return 0; 
}

运行结果:123456789

如果SRC的空间长度不够的话,运行就崩了。像这样。

2.memcpy是对内存的拷贝,不局限于字符串的拷贝。

_CRTIMP void * __cdecl memcpy(void * dest,const void * src,size_t n);

函数里面有三个参数,从SRC地址开始位置拷贝Ñ个字节长度到DEST的所指地址内存的起始位置,所以所每次的拷贝就把DEST指向的空间里面存放的内容覆盖掉了

#include <stdio.h> 
#include <string.h> 

int main(void){ 
	char dest [30]; 
	char * src =“djis \ 0sejfidsjfoi”; 
	int i; 
	FILE * fp; 

	memcpy(dest,src,sizeof(char)* 15); 
	dest [15] ='\ n'; //注意要加上0结束标志
	for(i = 0; 我<15; i ++){ 
		printf(“[%c]”,dest [i]); 
	} 

	return 0; 
}

虽然SRC字符串中间有一个\ 0但是拷贝的是一段内存上存放的值,最终还是会副本这一段字符串的内容到目中。

输出结果:[d] [j] [i] [s] [] [s] [e] [j] [f] [i] [d] [s] [j] [f] [o]

的memcpy不仅可以用于字符串拷贝,可以拷贝任何类型void *的,传递的参数可以指向任何类型。

可以拷贝一段数组元素

#include <stdio.h>
#include <string.h>

int main(void){ 
	int dest [10] = {0}; 
	int src [] = {1,2,3,4,5,6,7}; 
	int i; 

	memcpy(dest,src,sizeof(int)* 6); 
	for(i = 0; i<10; i ++){ 
		printf(“[%d]”,dest [i]); 
	} 

	return 0; 
}

输出结果:[1] [2] [3] [4] [5] [6] [0] [0] [0] [0]

3,memset的用于格式化一段内存,将一段内存全部设为某个字符

_CRTIMP void * __cdecl memset(void * src,int ch,size_t n);

将SRC开始后面Ñ个字节内存的内容都赋值为CH所对应的ASCLL码。

#include <stdio.h>
#include <string.h>

int main(void){ 
	char src [20]; 
	int i; 
	
	memset(SRC, 'X',10); 
	
	for(i = 0; i<20; i ++){ 
		printf(“[%c]”,src [i]); 
	} 

	return 0; 
}

输出结果:[X] [X] [X] [X] [X] [X] [X] [X] [X] [X] [] [] [] [] [] [] [] [] [ ] []

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值