开发者

first parameter in memset passing array or pointer

开发者 https://www.devze.com 2023-01-11 22:17 出处:网络
gcc 4.4.4 c89 Pointers are not the same as arrays. But arrays can decay into pointers. I was just using memset which first parameter is a pointer. I would like to initialize my structure array.

gcc 4.4.4 c89

Pointers are not the same as arrays. But arrays can decay into pointers.

I was just using memset which first parameter is a pointer. I would like to initialize my structure array.

i.e.

struct devices
{
    char name[STRING_SIZE];
    size_t profile;
    char catagory;
};

struct devices dev[NUM_DEVICES];开发者_JAVA技巧

memset(dev, 0, (size_t)NUM_DEVICES * sizeof(*dev));

dev == &dev[0]

But should I pass the first parameter has this:

 memset(&dev, 0, (size_t)NUM_DEVICES * sizeof(*dev));

Many thanks for any advice,


What you have:

memset(dev, 0, (size_t)NUM_DEVICES * sizeof(*dev));

is fine - you pass a pointer to the first element of the array, and the size of the array. However, the (size_t) cast is unnecessary (sizeof has type size_t, so it will cause the correct promotion) and I find that dev[0] is clearer than *dev in this case:

memset(dev, 0, NUM_DEVICES * sizeof dev[0]);

Alternatively, you can use &dev as the address. In this case, it is probably clearer to use sizeof dev - the size of the whole array:

memset(&dev, 0, sizeof dev);

I say that this is clearer, because it's generally best to have the first parameter be a pointer to the type that's the subject of sizeof in the last parameter: the memset() should look like one of these forms:

memset(p, ..., N * sizeof p[0])
memset(&x, ..., sizeof x)

Note however that this last one only works if dev really is an array - like it is in this case. If instead you have a pointer to the first element of the array, you'll need to use the first version.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号