Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

memcpy() ใน C/C++


ในบทความนี้ เราจะอภิปรายการทำงาน syntax และตัวอย่างของ memcpy() function ใน C++ STL

memcpy() คืออะไร?

memcpy() เป็น built-in function ใน C++ STL นิยามใน <cstring> header file ใช้ copy blocks of memory ใช้ copy จำนวนค่าจากหนึ่ง memory location ไปอีกที่

ผลลัพธ์คือ binary copy ของข้อมูล ฟังก์ชันนี้ไม่ตรวจสอบ terminating source หรือ terminating null character แค่ copy num bytes จาก source

ตัวอย่าง

void memcpy( void* destination, void* source, size_t num);

Parameters

ฟังก์ชันรับ parameter(s) ดังนี้ −

  • destination − pointer ไปยังตำแหน่งที่ต้องการเก็บผลลัพธ์
  • source − character string ที่ใช้เป็น input
  • num − จำนวน bytes ที่ต้อง copy

Return value

ฟังก์ชันคืนค่า pointer ไปยัง destination ที่ข้อมูลถูก copy ไป

ตัวอย่าง

Input

char str_1[10] = "Tutorials";
char str_2[10] = "Point";
memcpy (str_1, str_2, sizeof(str_2));

Output

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