“sizeof”的结果; C 中的结构数组?
在 C 中,我定义了一个结构数组,如下所示:
struct D
{
char *a;
char *b;
char *c;
};
static struct D a[] = {
{
"1a",
"1b",
"1c"
},
{
"2a",
"2b",
"2c"
}
};
我想确定数组中元素的数量,但 sizeof(a)
返回错误结果:48,而不是 2。我在做什么吗出了什么问题,还是 sizeof
这里根本不可靠?如果重要的话,我会使用 GCC 4.4 进行编译。
In C, I have an array of structs defined like:
struct D
{
char *a;
char *b;
char *c;
};
static struct D a[] = {
{
"1a",
"1b",
"1c"
},
{
"2a",
"2b",
"2c"
}
};
I would like to determine the number of elements in the array, but sizeof(a)
returns an incorrect result: 48, not 2. Am I doing something wrong, or is sizeof
simply unreliable here? If it matters I'm compiling with GCC 4.4.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个编译时常量,因此您可以使用它来创建另一个数组:
This is a compile-time constant, so you can use it to, for example, create another array:
sizeof
给出以字节为单位的大小,而不是元素的数量。正如 Alok 所说,要获取元素的数量,请将数组的大小(以字节为单位)除以一个元素的大小(以字节为单位)。正确的 C 习惯用法是:sizeof
gives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is:sizeof
返回传递的元素在内存中的大小。通过将数组的大小除以单个元素的大小,可以获得元素计数。请注意,元素大小也可能包括一些填充字节。因此,填充结构(例如,当 char 成员后跟指针时)的
sizeof
值将大于其成员大小总和。另一方面,在计算数组中的元素时,不要让它打扰您:
sizeof(a) / sizeof(a[0])
仍然会按预期顺利工作。sizeof
returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count.Note that the element size may include some padding bytes as well. For this reason, a padded struct (e.g. when a char member is followed by a pointer) will have a
sizeof
value greater than it members size sum.On the other hand, don't let it bother you when counting elements in an array:
sizeof(a) / sizeof(a[0])
will still work as smooth as expected.ssize_t portfoySayisi = sizeof(*portfoyler);
这个有效
ssize_t portfoySayisi = sizeof(*portfoyler);
THIS ONE WORKS