memset 函数学习

void *memset(void *s,int c,size_t n)

总的作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c。

这个函数通常用于清空所指长度的的内存。。。。

下面的例子是让所指的内存长度置为你想要的值

memset() 函数常用于内存空间初始化。如:
char str[100];
memset(str,0,100);

memset()的深刻内涵:用来对一段内存空间全部设置为某个字符,一般用在对定义的字符串进行初始化为‘ ’或‘/0’;例:char a[100];memset(a, '/0', sizeof(a));

memcpy用来做内存拷贝,你可以拿它拷贝任何数据类型的对象,可以指定拷贝的数据长度;例:char a[100],b[50]; memcpy(b, a, sizeof(b));注意如用sizeof(a),会造成b的内存地址溢出。

strcpy就只能拷贝字符串了,它遇到'/0'就结束拷贝;例:char a[100],b[50];strcpy(a,b);如用strcpy(b,a),要注意a中的字符串长度(第一个‘/0’之前)是否超过50位,如超过,则会造成b的内存地址溢出。

.补充:一点心得
memset可以方便的清空一个结构类型的变量或数组。

英文解释可能会更好

Fill block of memory

Sets the first num bytes of the block of memory pointed by ptr to the specifiedvalue (interpreted as an unsigned char).

Parameters

ptr
Pointer to the block of memory to fill.
value
Value to be set. The value is passed as an int, but the function fills the block of memory using theunsigned char conversion of this value.
num
Number of bytes to be set to the value.
/* memset example */ #include <stdio.h> #include <string.h> int main () { char str[] = "almost every programmer should know memset!"; memset (str,'-',6); puts (str); return 0; }


Output:


------ every programmer should know memset!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值