#include <stdio.h>
#include <string.h>
#include <stdint.h> // Cú pháp: void *memcpy(void* dest, const void *src, size_t n);
int main()
{ char src[] = "Hello World"; char dest[20]; uint8_t arr[] = { 1, 2, 3, 4}; uint32_t arr_variable; // Copy 13 bytes từ src sang dest memcpy(dest, src, strlen(src) + 1); // + 1 là thêm vị trí cho kí tự \n printf("Source: %s\n", src); printf("Destination: %s\n", dest); printf("dest[0] = %c\n", dest[0]); // Thử nghiệm với mảng printf("arr[0]: 0x%02X\n",arr[0]); memcpy(&arr_variable, arr, sizeof(arr_variable)); printf("arr_variable = %d\n", arr_variable); printf("arr_variable = 0x%X\n", arr_variable);
}
Output:
Source: Hello World
Destination: Hello World
dest[0] = H
arr[0]: 0x01
arr_variable = 67305985
arr_variable = 0x4030201
Qua kết quả trên ta nhận thấy được kết quả khi copy giá trị từ array sang 1 biến trong c bằng hàm memcpy()
là như thế nào
- Byte đầu tiên trong biến thì sẽ tương ứng với phần tử arr[0], và cứ tiếp tục lần lượt như vậy.
- Thứ tự sắp xếp các phần tự trong
arr
vàoarr_variable
dựa vàolittle-endian
(nghĩa là byte thấp, ít quan trọng nhất LSB sẽ đặt vào memory trước).