Whenever we use memset we set it with zero.
Why? Why not with 1 or 2 or something else.
Also, setting a struct to 0 seems to work but setting to 1 doesn't:
typedef struct abc{
int a;
} abc;
int main()
{
abc* ab;
memset(ab, 0, sizeof(abc));// it sets abc->a = 0; correct
}
But instead of 0 if I use 1 like:
memset(ab, 1, sizeof(abc));
then the value of abc->a = garbage or not equals to 1
Why?
You don't always need to memset to 0, this is just the most common (and useful) thing to do.
memset sets each byte to some given value. An int consists of 4 bytes, so, when memseting to 1, you'd set each of those 4 to 1, then you'd have 00000001 | 00000001 | 00000001 | 000000012 = 1684300910 (the first numbers are in binary, the last in decimal).
Also - note that you're never allocating memory for ab. Even though your code may work now, it's not safe. This would be:
abc ab;
memset(&ab, 0, sizeof(abc));
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