'sizeof' 在 C 中的结构数组上的结果? [英] Result of 'sizeof' on array of structs in C?
本文介绍了'sizeof' 在 C 中的结构数组上的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C 中,我定义了一个结构数组,如下所示:
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"
}
};
我想确定数组中元素的数量,但是sizeof(a)
返回了错误的结果:48,而不是2.我做错了什么,还是sizeof
在这里根本不可靠?如果重要的话,我正在使用 GCC 4.4 进行编译.
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.
推荐答案
sizeof a / sizeof a[0];
这是一个编译时常量,因此您可以使用它来创建另一个数组:
This is a compile-time constant, so you can use it to, for example, create another array:
#define N sizeof a / sizeof a[0]
int n_a[N];
这篇关于'sizeof' 在 C 中的结构数组上的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文