Question

I've read the function headers, but I'm still not sure what exactly the difference is in terms of use cases.

Was it helpful?

Solution

memcpy() copies from one place to another. memset() just sets all pieces of memory to the same value.

Example:

memset(str, '*', 50);   

The above line sets the first 50 characters of the string str to * (or whatever second argument of the memset).

memcpy(str2, str1, 50); 

The above line copies the first 50 characters of str1 to str2.

OTHER TIPS

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|
* +-+-+-+-+
*/

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.

memset fill memory with constant byte

void *memset(void *s, int c, size_t n);

Use of memset is programmer can directly fill memory with particular. and memcpy uses constant void pointer to source which cannot be changed.

memcpy copy the memory area

void *memcpy(void *dest, const void *src, size_t n);

Reference memcpy memset

memcpy() copies from one place to another. memset() just sets all pieces of memory to the same.

For example here sets string length of the string str to * (or whatever second argument of the memset).

memset(str, '*', strlen(str)+1);   

Here copies the string length of the string src to dest.

memcpy(dest, src, strlen(src)+1);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top