What's the usefulness of the function memset()
?.
Definition: Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Does this mean it hard codes a value in a memory address?
memset(&serv_addr,0,sizeof(serv_addr)
is the example that I'm trying to understand.
Can someone please explain in a VERY simplified way?
Description. The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.
memset() is built in standard string function that is defined in string header library string. h .
memset in C++ In this section we will see what is the purpose of memset() function in C++. This function converts the value of a character to unsigned character and copies it into each of first n character of the object pointed by the given str[]. If the n is larger than string size, it will be undefined.
The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
memset()
is a very fast version of a relatively simple operation:
void* memset(void* b, int c, size_t len) { char* p = (char*)b; for (size_t i = 0; i != len; ++i) { p[i] = c; } return b; }
That is, memset(b, c, l)
set the l
bytes starting at address b
to the value c
. It just does it much faster than in the above implementation.
memset()
is usually used to initialise values. For example consider the following struct:
struct Size { int width; int height; }
If you create one of these on the stack like so:
struct Size someSize;
Then the values in that struct are going to be undefined. They might be zero, they might be whatever values happened to be there from when that portion of the stack was last used. So usually you would follow that line with:
memset(&someSize, 0, sizeof(someSize));
Of course it can be used for other scenarios, this is just one of them. Just think of it as a way to simply set a portion of memory to a certain value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With