memcpy and memset
Raw memory functions.
Raw memory functions
Unlike string functions, memcpy and memset work on raw bytes and ignore null terminators.
They are declared in <string.h> and operate on a count of bytes you specify, making them general-purpose for any data type.
#include <stdio.h>
#include <string.h>
int main(void) {
int src[] = {1, 2, 3};
int dest[3];
memcpy(dest, src, sizeof(src));
printf("%d %d %d\n", dest[0], dest[1], dest[2]);
return 0;
}The memcpy signature
void *memcpy(void *dest, const void *src, size_t n);
It copies exactly n bytes from src to dest and returns dest. Use sizeof to get the right byte count.
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "copy me";
char dest[16];
memcpy(dest, src, strlen(src) + 1);
printf("%s\n", dest);
return 0;
}All lessons in this course
- strlen, strcpy, strcat
- strcmp and Comparison
- strtok and Tokenizing
- memcpy and memset