`
kanwoerzi
  • 浏览: 1643092 次
文章分类
社区版块
存档分类
最新评论

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.


Output:


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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics