 |
#include <stdio.h> #include <string.h>
int main() { char ch[] = "This is a pen."; memset(ch + 3, '*', 8); // begins at the 4th char printf("%s\n", ch); // Result: Thi********en. return 0; }
|
 |
memset是計算機中C/C++語言函數。將s所指向的某一塊內存中的前n個 字節的內容全部設置為ch指定的ASCII值
|
 |
#include <stdio.h> #include <string.h> // for memset #include <stdlib.h> // for calloc
int main() { char* ch = calloc(15, sizeof(char)); memset(ch, 'A', 14); printf("%s\n", ch); memset(ch + 3, '\0', 1); printf("%s\n", ch); memset(ch + 3, 'B', 1); printf("%s\n", ch); return 0; } /* AAAAAAAAAAAAAA AAA AAABAAAAAAAAAA */
|
 |
memset(ch + 3, '\0', 1); At the 3 + 1 th char, repeat '\0' one time.
|
 |
另外,如果把「This is a pen.「中的首字母T看作第0個字符的話(ch + 0),那麼ch + 3就是第3個字符「s」,這個和數組是差不多的。數組下標也是從0開始的。
|