-2

I tried memset to assign all the structure members to 0 as given below, but it didn't work.

struct sample
{
    int a;
    int b;
    int c;
    int d;
    int e; 
    int f;
};

int main(void)
{
    struct sample s1;

    memset(&s1, 1, sizeof(s1));
    printf("%d",s1.e);

    return 0; 
}

3 Answers3

0

memset can be used to initialize an object to all bits zero, which is appropriate to set all int member values to 0.

For non zero initial values, there are several alternatives:

    struct sample s1 = { 1, 1, 1, 1, 1, 1 }; // using an initializer

or

    struct sample s1;
    s1.a = s1.b = s1.c = s1.d = s1.e = s1.f = 1;  // initializing the members explicitly

or

    static struct sample default_sample = { 1, 1, 1, 1, 1, 1 };
    struct sample s1 = default_sample; // copying values from another structure.
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-1

I tried memset to assign all the structure members to 0

 memset(&s1, 1, sizeof(s1));

This will definitely not zero the struct members.

And this will:

memset(&s1, 0, sizeof(s1));

If you want to set them to the another value you need to answer one question : How portable do you want it to be?

The portable way:

 struct sample s1 = { 1,1,1,1,1,1};  // initialisation

s1.a = 1;
s1.b = 1;
s1.b = 1;
s1.d = 1;
s1.e = 1;
s1.f = 1;

Non portable way (assuming the same type and no padding between members):

#define NMEMBERS 6
int *ptr = (void *)&s1;
for(int index = 0; index < NMEMBERS; index++, ptr++)
{
    *ptr = 1;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
-2
memset(&s1, 1, sizeof(s1));

The above code doesn’t set structure members to 1 as memset works byte by byte. Hence each byte of your structure will have value 1

If you want to initialize the structure members other than 0. You can do as below.

struct sample s1 = { 1,1,1,1,1,1}; 

or Initialize each members separately after declaration.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44