The manpage says about memset
:
#include <string.h> void *memset(void *s, int c, size_t n)
The
memset()
function fills the firstn
bytes of the memory area pointed to bys
with the constant bytec
.
It is obvious that memset
can't be used to initialize int
array as shown below:
int a[10];
memset(a, 1, sizeof(a));
it is because int
is represented by 4 bytes (say) and one can not get the desired value for the integers in array a
.
But I often see the programmers use memset
to set the int
array elements to either 0
or -1
.
int a[10];
int b[10];
memset(a, 0, sizeof(a));
memset(b, -1, sizeof(b));
As per my understanding, initializing with integer 0
is OK because 0
can be represented in 1 byte (may be I am wrong in this context). But how is it possible to initialize b
with -1
(a 4 bytes value)?
0
is OK. It is OK because0
fits in anunsigned char
(so it is not truncated when used as the second argument tomemset
) and because the bit pattern in memory for asizeof(int)
-byte zero is identical to the bit pattern in memory forsizeof(int)
sequential one-byte zeros. Both of those things must be true for this to work. In fact, those things are true for exactly two numbers in twos-complement arithmetic:0
and-1
. – zwolint
with value x are the same as the bits forsizeof(int)
unsigned char
each with the value x. Further, we must consider theunsigned char
with value x as resulting from conversion of x tounsigned char
, as −1 is not representable. If so, then it is not true that 0 and −1 are the only such values. 16,843,009 • x works for any integer 0 ≤ x < 256. (16,843,009 is hex 1010101). – Eric Postpischilchar
types (well, unless you're on a machine whereCHAR_BIT >= 25
.) – zwol