简体   繁体   English

使用memset初始化结构数组

[英]initializing a structure array using memset

gcc 4.4.4 c89 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. 当我调用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. 请注意,在所有变体的特定情况下,您可以使用&dev_sysdev_sys作为第一个参数。 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. 但是, &dev_sys在第一个变体中更合适,因为如果遵循memset(ptr-to-object, object-size)习语。 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. 在第二和第三个变体中,使用dev_sys (或&dev_sys[0] )更合适,因为它遵循memset(ptr-to-first-element, number-of-elements * element-size)习语。

PS Of course, instead of using all that hackish memset trickery, in your particular case you should have just declared your array with an initializer PS当然,在您的特定情况下,您应该使用初始化程序声明您的数组,而不是使用所有那些hackish memset技巧

struct device_sys dev_sys[NUM_DEVICES] = { 0 };

No memset necessary. 不需要memset

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". 我推荐“设备”。

You have to pass the sizeof operator the type and not the variable. 您必须传递sizeof运算符的类型而不是变量。

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

I prefer to use typedef for the struct. 我更喜欢使用typedef作为结构。

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

The you can use memset as follows: 你可以使用memset如下:

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

For an array, sizeof gets you the entire size of the array, not the size of an individual element. 对于数组, sizeof可以获得数组的整个大小,而不是单个元素的大小。 The sizeof operator is one of the few places where an array is not treated as a pointer to its first element. sizeof运算符是少数几个不将数组视为指向其第一个元素的指针的地方之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM