memset
|
Routine |
Required header |
|---|---|
|
memset |
<memory.h> or <string.h> |
|
wmemset |
<wchar.h> |
<cstring>void * memset ( void * ptr, int value, size_t num );
Fill block of memory
Sets the first num bytes of the block of memory pointed by ptr to the specifiedvalue (interpreted as anunsigned 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 thisvalue. num
- Number of bytes to be set to the value.
Return Value
ptr is returned.Example
| 1 2 3 4 5 6 7 8 9 10 11 |
|
Output:
------ every programmer should know memset!
注:需要注意的是memset是对第一个参数(指针)所指向的内存中(长度为第三个参数,单位是字节数),每个字节置为字符的ASCII码
也就是说不是以数据类型为单位进行置位的
int a[10];
memset(a,10,sizeof(a));
结果是把a所指向的内存区域每个字节置成了ASCII码10,那么结果自然不是想要的,也就是10 10 10 10(简写的),意思是4个字节中,每个内存都是10,4个自然不是咯!
但是可以给int(float……)或指针行数组初始化成0的;
int a[10];
memset(a,0,sizeof(a));
原理已经讲过了,就不再重复;
要想对int数组,或其他任意数组进行片操作,可以使用STL里的函数模板(fill)
需加头文件
#include <algorithm>
fill
<algorithm>template < class ForwardIterator, class T > void fill ( ForwardIterator first, ForwardIterator last, const T& value );
Fill range with value
Sets value to all elements in the range [first,last).The behavior of this function template is equivalent to:
| 1 2 3 4 5 |
|
Parameters
- first, last
- Forward iterators to the initial and final positions in a sequence. The range affected is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. value
- Value to be used to fill the range.
Return value
noneExample
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Output:
myvector contains: 5 5 5 8 8 8 0 0 |
对数组进行操作就是
int a[10];
std::fill(a,//数组名,也就是首地址
a+10,//首地址+长度,也就是迭代器下一位,这样2个参数就是[a,a[10])<=>a[0]~a[9]
5)//想要置位的值
类似,可以对任何类型的数组操作!
本文详细介绍了C++内存填充函数memset的用法、参数解释、返回值及实例演示,并阐述了如何利用STL中的fill函数进行内存填充,提供了一段使用示例代码及其输出结果。
15万+

被折叠的 条评论
为什么被折叠?



