ในส่วนนี้เราจะมาดูกันว่าฟังก์ชั่น memset() มีจุดประสงค์อะไรในภาษา C++ ฟังก์ชันนี้แปลงค่าของอักขระให้เป็นอักขระที่ไม่ได้ลงนาม และคัดลอกลงในอักขระ n ตัวแรกของวัตถุที่ชี้โดย str[] ที่กำหนด หาก n ใหญ่กว่าขนาดสตริง จะไม่มีการกำหนด
ไวยากรณ์ของฟังก์ชัน memset()
void* memset( void* str, int c, size_t n);
ในตัวอย่างนี้จะใช้หนึ่งสตริง จากนั้นแปลงอักขระแต่ละตัวเป็นอักขระอื่นที่มีความยาวไม่เกิน n
ตัวอย่าง
#include<bits/stdc++.h>
using namespace std;
int main() {
char str[] = "Hello World";
memset(str, 'o', 6); //take n = 6
cout << str;
} ผลลัพธ์
ooooooWorld
สามารถใช้ memset() เพื่อตั้งค่าทั้งหมดเป็น 0 หรือ -1 แต่เราไม่สามารถใช้ค่าอื่นได้ เนื่องจาก memset() ทำงานทีละไบต์
ตัวอย่าง
#include<bits/stdc++.h>
using namespace std;
int main() {
int array[10];
memset(array, 0, sizeof(array));
for(int i = 0; i<10; i++){ cout << array[i] << " "; }
cout << endl;
memset(array, -1, sizeof(array));
for(int i = 0; i<10; i++){ cout << array[i] << " "; }
cout << endl;
memset(array, 3, sizeof(array));
for(int i = 0; i<10; i++){ cout << array[i] << " "; }
cout << endl;
} ผลลัพธ์
0 0 0 0 0 0 0 0 0 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 50529027 50529027 50529027 50529027 50529027 50529027 50529027 50529027 50529027 50529027