Tutorial :initializing a structure array using memset



Question:

gcc 4.4.4 c89

I have the following structure.

struct device_sys  {      char device[STRING_SIZE];      int id;      char category;  };    int main(void)  {      struct device_sys dev_sys[NUM_DEVICES];        memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));        return 0;   }  

I get a stack dump when I call memset. Is this not the correct way to initialize an structure array?


Solution:1

Either

memset(&dev_sys, 0, sizeof dev_sys);  

or

memset(dev_sys, 0, NUM_DEVICES * sizeof(struct device_sys));  

Or, if you prefer

memset(dev_sys, 0, NUM_DEVICES * sizeof *dev_sys);  

but not what you have in your original variant.

Note, that in your specific case in all variants you can use either &dev_sys or dev_sys as the first argument. The effect will be the same. However, &dev_sys is more appropriate in the first variant, since if follows the memset(ptr-to-object, object-size) idiom. In the second and third variants it is more appropriate to use dev_sys (or &dev_sys[0]), since it follows the memset(ptr-to-first-element, number-of-elements * element-size) idiom.

P.S. Of course, instead of using all that hackish memset trickery, in your particular case you should have just declared your array with an initializer

struct device_sys dev_sys[NUM_DEVICES] = { 0 };  

No memset necessary.


Solution:2

There's a typo in your code. Fix:

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(struct device_sys));  

Picking good names avoid half the bugs. I'd recommend "devices".


Solution:3

You have to pass the sizeof operator the type and not the variable.

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(struct device_sys));  

I prefer to use typedef for the struct.

typedef struct tag_device_sys  {      char device[STRING_SIZE];      int id;      char category;  } device_sys;  

The you can use memset as follows:

    memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));  


Solution:4

For an array, sizeof gets you the entire size of the array, not the size of an individual element. The sizeof operator is one of the few places where an array is not treated as a pointer to its first element.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »