memcpy function-copy memory area in bytes
The memcpy function is a function that copies a memory area in bytes. Include "string.h".
#include <string.h> void * memcpy (void * buf1, const void * buf2, size_t n);
The first argument is the address of the copy destination. General-purpose pointer type, so any pointer type is fine.
The second argument is the address of the copy source. General-purpose pointer type, so any pointer type is fine.
Specify the byte size in the third argument. It is size_t type. int32_t If the value is 0 or more in the range up to the type, it is safe first. Specifying 0 is a valid argument, in which case no copy will be done.
Operation is not guaranteed if the copy destination and copy source data areas overlap. Use the memmove function to operate correctly even if the copy destination and copy source data areas overlap. If they do not overlap, use the memcpy function, which gives priority to performance.
Copy the string
This is a sample to copy a character string with the memcpy function. Get the length of the string with strlen function, with calloc function A memory area is secured, and a process called copying is performed to that area with the memcpy function. If the copy destination variable has the const qualifier, it cannot be copied, so it is copied to a temporary character string without the const qualifier.
#include <stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int main (void) { // string const char * message = "Hello"; // String length int32_t message_length = strlen (message); // Secure memory area char * new_message_tmp = calloc (sizeof (char), message_length + 1); // Copy to a temporary string with the memcpy function memcpy (new_message_tmp, message, message_length); // Assign to a new string (because I want to add the const modifier) const char * new_message = new_message_tmp; new_message_tmp = NULL; printf("%s\n", new_message); }
This is the output result.
Hello
Copy an array of signed 32-bit integers
This is a sample to copy array of int32_t --signed 32-bit integer with the memcpy function. .. The calloc function allocates a memory area, and the memcpy function copies it to that area. Note that the length to copy is "element type size x array length". The for statement outputs the elements of the array.
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> int main (void) { // arrangement int32_t nums_length = 3; int32_t nums [] = {3, 5, 7}; // Secure memory area int32_t * new_nums = calloc (sizeof (int32_t), nums_length); // Copy an array of type int32_t with the memcpy function memcpy (new_nums, nums, sizeof (int32_t) * nums_length); for (int32_t i = 0; i <nums_length; i ++) { printf("nums [%d]:%d\n", i, new_nums [i]); } }
This is the output result.
nums [0]: 3 nums [1]: 5 nums [2]: 7