Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between memset and memcpy in C

Tags:

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

like image 830
Dirk Avatar asked Oct 08 '09 06:10

Dirk


People also ask

Is memset faster than memcpy?

Notice that memcpy is only slightly slower then memset . The operations a[j] += b[j] (where j goes over [0,LEN) ) should take three times longer than memcpy because it operates on three times as much data. However it's only about 2.5 as slow as memset .

What is memcpy in c?

memcpy() function in C/C++ The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string. h” header file in C language.

What is the difference between memcpy and strcpy?

strcpy () is meant for strings only whereas memcpy() is generic function to copy bytes from source to destination location. The strcpy ( ) function is designed to work exclusively with strings.

What is memset in c?

The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.


1 Answers

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.

like image 150
Peter Avatar answered Sep 24 '22 21:09

Peter