-4

Consider the below structure

struct A
{
    int len;
    int wid;
    int size;
};

void main()
{
    struct A var;
    memset(&var,10,sizeof(struct A));
    printf("value of len is %d\n",var.len);
}

When I run the program, I was expecting that all the structure members will get initialized with 10 but it didn't happened. It was printing some junk value

But when I do memset with 0 or memset with 1 it works.

memset(&var,0,sizeof(struct A));
printf("value of len is %d\n",var.len);

Can someone please explain this behavior of memset

vivek
  • 467
  • 2
  • 6
  • 18
  • 1
    Read [memset](http://en.cppreference.com/w/c/string/byte/memset) – BLUEPIXY Jul 31 '17 at 10:48
  • You expected the output of `printf()` to be `10`. You expected wrongly. Consider. ;-) It doesn't print "some address", it prints *exactly* what you did set `var.len` to. Consider that as well. ;-) – DevSolar Jul 31 '17 at 10:54
  • This is not the same question as the alleged duplicate. That one was abourt arrays, this is about structs – JeremyP Jul 31 '17 at 10:59

1 Answers1

3

memset fills the memory with byte values. Your int members most probably need more than one byte (depending on your platform, four is quite common). So you're writing bytes and interpret them as int.

Your second example works as expected, because an all-zero representation of an int is required to be interpreted as the value 0.