语法:
#include <cstring> void* memset( void* buffer, int ch, size_t count );
memset()拷贝ch至buffer的前count字符中,并返回buffer。memset()对于以某一值初始化一段内存非常有用。例如,这个命令:
const int ARRAY_LENGTH = 300; char the_array[ARRAY_LENGTH]; ... // zero out the contents of the_array memset( the_array, '\0', ARRAY_LENGTH );
…是非常有效率的方法来设置the_array中的所有值为零。
下表比较了两种不同的方式来初始化字符数组:for循环和memeset()。随着初始化数据量的增加,memset()很清晰的做的更快:
| 输入量 | for循环初始化 | memset()初始化 |
|---|---|---|
| 1000 | 0.016 | 0.017 |
| 10000 | 0.055 | 0.013 |
| 100000 | 0.443 | 0.029 |
| 1000000 | 4.337 | 0.291 |