memcpy() is used to copy a block of memory from a location to another. It is declared in string.h
// Copies "numBytes" bytes from address "from" to address "to" void * memcpy(void *to, const void *from, size_t numBytes);
Below is a sample C program to show working of memcpy().
/* A C program to demonstrate working of memcpy */#include <stdio.h> #include <string.h> int main () { char str1[] = "Geeks"; char str2[] = "Quiz"; puts("str1 before memcpy "); puts(str1); /* Copies contents of str2 to sr1 */ memcpy (str1, str2, sizeof(str2)); puts("\nstr1 after memcpy "); puts(str1); return 0; } |
chevron_right
filter_none
Output:
str1 before memcpy Geeks str1 after memcpy Quiz
Notes:
1) memcpy() doesn’t check for overflow or \0
2) memcpy() leads to problems when source and destination addresses overlap.
memmove() is another library function that handles overlapping well.
Write your own memcpy() and memmove()
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
Recommended Posts:
- Write your own memcpy() and memmove()
- Higher Order Functions in C++
- How to get element at specific position in List in C++
- Iterate over characters of a string in C++
- Difference between int (*p)[3] and int* p[3]?
- 3-way comparison operator (Space Ship Operator) in C++ 20
- How to generate a vector with random values in C++?
- Difference between std::set vs std::vector in C++ STL
- Vector of Maps in C++ with Examples
- Data Conversion in C++
- Order of execution in initializer list in C++
- Unusual behaviour with character pointers
- Header Guard in C++
- Can we write a print statement within if parentheses?

