memset 中的第一个参数传递数组或指针
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你所拥有的:
很好 - 你传递一个指向数组第一个元素的指针以及数组的大小。但是,
(size_t)
转换是不必要的(sizeof
具有类型size_t
,因此它将导致正确的提升),我发现dev[0] 比
*dev
更清晰:或者,您可以使用
&dev
作为地址。在这种情况下,使用 sizeof dev 可能更清楚 - 整个数组的大小:我说这更清楚,因为通常最好让第一个参数是指向该类型的指针最后一个参数中
sizeof
的主题:memset()
应该类似于以下形式之一:但请注意,最后一个仅在
dev
时才有效code> 实际上是一个数组 - 就像在本例中一样。相反,如果您有指向数组第一个元素的指针,则需要使用第一个版本。What you have:
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 typesize_t
, so it will cause the correct promotion) and I find thatdev[0]
is clearer than*dev
in this case:Alternatively, you can use
&dev
as the address. In this case, it is probably clearer to usesizeof dev
- the size of the whole array: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: thememset()
should look like one of these forms: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.