ในส่วนนี้เราจะดูว่า memset() ใน C++ ทำหน้าที่อะไร ฟังก์ชันนี้แปลงค่าของ character ให้เป็น unsigned character และคัดลอกไปยังตัวอักษร n ตัวแรกของอ็อบเจ็กต์ที่ str[] ชี้ไป หาก n ใหญ่กว่าขนาดสตริง จะเป็น undefined behavior
ไวยากรณ์ของ memset()
void* memset(void* str, int c, size_t n);
ในตัวอย่างนี้จะใช้สตริงหนึ่ง แล้วแปลงตัวอักษรแต่ละตัวให้เป็นอีกตัวอักษรหนึ่ง จนถึงความยาว n
ตัวอย่างที่ 1
#include <bits/stdc++.h>
using namespace std;
int main() {
char str[] = "Hello World";
memset(str, 'o', 6); // กำหนด n = 6
cout << str;
}
ผลลัพธ์
ooooooWorld
memset() สามารถใช้เซ็ตค่าทั้งหมดเป็น 0 หรือ -1 ได้ แต่ไม่ควรใช้ค่าอื่น เพราะ memset() ทำงานแบบ byte-by-byte
ตัวอย่างที่ 2: การใช้งานกับอาร์เรย์ integer
#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)); // ไม่ควรทำกับค่าอื่นนอกจาก 0 และ -1
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
หมายเหตุ: การใช้ memset กับค่า 3 ให้ผลลัพธ์ที่ไม่คาดคิด เพราะ 3 ในรูปแบบ byte คือ 0x03 และ integer 4 bytes จะกลายเป็น 0x03030303 = 50529027