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?
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.
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