memset 中的第一个参数传递数组或指针

发布于 2024-09-13 19:46:56 字数 460 浏览 2 评论 0原文

gcc 4.4.4 c89

指针与数组不同。但数组可以退化为指针。

我只是使用 memset,第一个参数是一个指针。我想初始化我的结构数组。

ie

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

struct devices dev[NUM_DEVICES];

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

dev == &dev[0]

但是我应该传递第一个参数吗:

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

非常感谢您的任何建议,

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];

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞美少年 2024-09-20 19:46:56

你所拥有的:

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

很好 - 你传递一个指向数组第一个元素的指针以及数组的大小。但是, (size_t) 转换是不必要的(sizeof 具有类型 size_t,因此它将导致正确的提升),我发现dev[0] 比 *dev 更清晰:

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

或者,您可以使用 &dev 作为地址。在这种情况下,使用 sizeof dev 可能更清楚 - 整个数组的大小:

memset(&dev, 0, sizeof dev);

我说这更清楚,因为通常最好让第一个参数是指向该类型的指针最后一个参数中 sizeof 的主题:memset() 应该类似于以下形式之一:

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

但请注意,最后一个仅在 dev 时才有效code> 实际上是一个数组 - 就像在本例中一样。相反,如果您有指向数组第一个元素的指针,则需要使用第一个版本。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文