ในบทความนี้เราจะพูดถึงการทำงาน ไวยากรณ์และตัวอย่างของฟังก์ชัน memcpy() ใน C++ STL
memcpy() คืออะไร
ฟังก์ชัน memcpy() เป็นฟังก์ชัน inbuilt ใน C++ STL ซึ่งกำหนดไว้ในไฟล์ส่วนหัว
ผลลัพธ์ของฟังก์ชันคือสำเนาไบนารีของข้อมูล ฟังก์ชันนี้ไม่ตรวจสอบแหล่งที่มาที่สิ้นสุดหรืออักขระ null ใดๆ ที่สิ้นสุด แต่จะคัดลอกจำนวนไบต์จากแหล่งที่มา
ตัวอย่าง
void memcpy( void* destination, void* source, size_t num);
พารามิเตอร์
ฟังก์ชันยอมรับพารามิเตอร์ต่อไปนี้ -
- ปลายทาง − นี่คือตัวชี้ไปยังตำแหน่งที่เราต้องการให้จัดเก็บเอาต์พุต
- ที่มา − สตริงอักขระที่ใช้เป็นอินพุต
- จำนวน − เป็นจำนวนไบต์ที่จะคัดลอก
คืนค่า
ฟังก์ชันนี้จะส่งคืนตัวชี้ไปยังปลายทางที่จะคัดลอกข้อมูล
ตัวอย่าง
อินพุต
char str_1[10] = "Tutorials"; char str_2[10] = "Point"; memcpy (str_1, str_2, sizeof(str_2));
ผลลัพธ์
string str_1 before using memcpy Tutorials string str_1 after using memcpy Point
ตัวอย่าง
#include <stdio.h>
#include <string.h>
int main (){
char str_1[10] = "Tutorials";
char str_2[10] = "Point";
puts("string str_1 before using memcpy ");
puts(str_1);
memcpy (str_1, str_2, sizeof(str_2));
puts("\nstring str_1 after using memcpy ");
puts(str_1);
return 0;
} ผลลัพธ์
string str_1 before using memcpy Tutorials string str_1 after using memcpy Point
ตัวอย่าง
#include <stdio.h>
#include <string.h>
int main (){
char str_1[10] = "Tutorials";
char str_2[10] = "Point";
puts("string str_1 before using memcpy ");
puts(str_1);
memcpy (str_1,str_2, sizeof(str_2));
puts("\nstring str_2 after using memcpy ");
puts(str_2);
return 0;
} ผลลัพธ์
string str_1 before using memcpy Tutorials string str_2 after using memcpy Point