[英]How to get size of inner structure
I'm trying to get size of inner structure ie struct B
. 我正在尝试获取内部结构(即
struct B
大小。 But I'm getting compilation error: 但是我收到编译错误:
prog.c: In function 'main': prog.c:10:53: error: expected ')' before ':' token printf("%d | %d", sizeof(struct A), sizeof(struct A::struct B));
prog.c:在函数'main'中:prog.c:10:53:错误:预期的')'在':'令牌之前printf(“%d |%d”,sizeof(struct A),sizeof(struct A: :struct B));
Following is my code: 以下是我的代码:
#include <stdio.h>
struct A
{
struct B{};
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct A::struct B));
return 0;
}
Could you suggest that how I can achieve this in C? 你能建议我如何用C语言实现吗?
UPDATED 更新
Answer from @Jabberwocky solves my above problem. @Jabberwocky的答案解决了我上面的问题。 But What about following code.
但是下面的代码呢? This can also be found here :
也可以在这里找到:
#include <stdio.h>
struct A
{
struct B{};
};
struct B
{};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B), sizeof(struct A::struct B));
return 0;
}
In this case I'm getting compilation error as following: 在这种情况下,我得到如下编译错误:
prog.c:8:8: error: redefinition of 'struct B'
prog.c:8:8:错误:“结构B”的重新定义
struct B结构B
^^
prog.c:5:10: note: originally defined hereprog.c:5:10:注意:最初在此处定义
struct B{};结构B {};
^^
prog.c: In function 'main':prog.c:在函数“ main”中:
prog.c:12:71: error: expected ')' before ':' tokenprog.c:12:71:错误:在':'标记之前应有预期的')'
printf("%d | %d", sizeof(struct A), sizeof(struct B), sizeof(struct A::struct B));printf(“%d |%d”,sizeof(结构A),sizeof(结构B),sizeof(结构A ::结构B));
Here how I can diffrentiate between struct B
and struct A::struct B
在这里,我如何区分
struct B
和struct A::struct B
#include <stdio.h>
struct A
{
struct B{}; // this should not compile anyway in C as C
// does not allow empty structs
// but this would compile: struct B{int a;};
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B));
// just write struct B
return 0;
}
Working sample: 工作样本:
#include <stdio.h>
struct A
{
int b;
struct B { int a; };
};
int main() {
printf("%d | %d", sizeof(struct A), sizeof(struct B));
return 0;
}
Possible output on a 32 bit system: 在32位系统上可能的输出:
8 | 4
Be aware that C support for nested structures is logical only. 请注意,C对嵌套结构的支持仅是逻辑上的。 Each structure exists on its own.
每个结构都独立存在。
#include <stdio.h>
struct A { // same as
int bar; // struct B { int foo };
struct B { int foo; } b; // struct A { int bar; struct B b; };
};
int main(void) {
struct A a;
a.bar = 42;
a.b.foo = -1;
printf("a.bar is %d; a.b.foo is %d\n", a.bar, a.b.foo);
struct B b; /* struct B is visible outside struct A */
b.foo = 666;
printf("b.foo - a.bar is %d\n", b.foo - a.bar);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.