What is the difference between memcpy() and strcpy() in C?
| strcpy() | memcpy() |
|---|---|
| Only for strings | For any data (int arrays, structures) |
| Stops at the null character | Copies exactly n bytes |
| Does not need a size | Needs the number of bytes |
#include <stdio.h>
#include <string.h>
int main(void) {
int a[3] = {1, 2, 3};
int b[3];
memcpy(b, a, sizeof(a));
printf("%d %d %d\n", b[0], b[1], b[2]);
return 0;
}
Output:
Output of the above program is
1 2 3
For overlapping memory use memmove(), because memcpy() does not handle it.
Learn more about the similar topics:
| Tutorials |
|---|
| C Arrays |
| C Two Dimensional Arrays |
| C Passing Arrays to Functions |
| C Strings |
| C String Input and Output |
| C String Functions |
| C strlen() Function |
| Interview Questions & Answers |
|---|
| What is an array in C? |
| How is a string stored in C? |
| How to reverse a string in C? |
| What is the difference between memcpy() and strcpy() in C? |