I've read the function headers, but I'm still not sure what exactly the difference is in terms of use cases.
Thanks!
I've read the function headers, but I'm still not sure what exactly the difference is in terms of use cases.
Thanks!
memset()
sets all of the bytes in the specified buffer to the same value, memcpy()
copies a sequence of bytes from another place to the buffer.
char a[4];
memset(a, 7, sizeof(char)*4);
/*
* a is now...
*
* +-+-+-+-+
* |7|7|7|7|
* +-+-+-+-+
*/
char b[] = {1,2,3,4};
char c[4];
memcpy(c, b, sizeof(char)*4);
/*
* c is now...
*
* +-+-+-+-+
* |1|2|3|4|
* +-+-+-+-+
*/
memcpy
copies from one place to another. memset
just sets all pieces of memory to the same.
example:
memset(str, '*', 50); // sets the first 50 characters of the string str to *.
memcpy(str2, str1, 50); // copies the first 50 characters of str1 to str2.
memset
sets a block of memory to a single value. memcpy
copies the content of a block into another block.
Perhaps you'd be interested in the difference between memcpy
and memmove
. Both do the same, but the latter works even if the source and destination overlap.
memset()
is used to set all the bytes in a block of memory to a particular char value. Memset also only plays well with char
as it's its initialization value.
memcpy()
copies bytes between memory. This type of data being copied is irrelevant, it just makes byte-for-byte copies.