C++ 程式設計/程式碼/標準 C 庫/函式/memset
外觀
| 語法 |
#include <cstring>
void* memset( void* buffer, int ch, size_t count );
|
函式 memset() 將 ch 複製到 buffer 的前 count 個字元中,並返回 buffer。 memset() 用於將記憶體部分初始化為某個值。例如,以下命令
const int ARRAY_LENGTH;
char the_array[ARRAY_LENGTH];
...
// zero out the contents of the_array
memset( the_array, '\0', ARRAY_LENGTH );
... 是一種非常高效的方法,可以將 the_array 的所有值設定為零。
下表比較了兩種初始化字元陣列的不同方法: for 迴圈與 memset()。 隨著正在初始化的資料大小的增加,memset() 顯然可以更快地完成工作。
| 輸入大小 | 使用 for 迴圈初始化 |
使用 memset() 初始化 |
|---|---|---|
| 1000 | 0.016 | 0.017 |
| 10000 | 0.055 | 0.013 |
| 100000 | 0.443 | 0.029 |
| 1000000 | 4.337 | 0.291 |