如何获得内部结构的大小

cse*_*cse 1 c sizeof

我正试图获得内部结构的大小,即struct B.但我收到编译错误:

prog.c:在函数'main'中:prog.c:10:53:error:expected')'before':'token printf("%d |%d",sizeof(struct A),sizeof(struct A: :struct B));

以下是我的代码:

#include <stdio.h>

struct A
{
        struct B{};
};

int main() {
    printf("%d | %d", sizeof(struct A), sizeof(struct A::struct B));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您能否建议我如何在C中实现这一目标?

更新

来自@Jabberwocky的回答解决了我上面的问题.但是如何遵循代码呢.这也可以在这里找到:

#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;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我得到编译错误如下:

prog.c:8:8:错误:重新定义'struct
B'struct B
^
prog.c:5:10:注意:最初在这里定义
struct B {};
^
prog.c:在函数'main'中:
prog.c:12:71:error:expected')'before':'token
printf("%d |%d",sizeof(struct A),sizeof(struct B) ),sizeof(struct A :: struct B));

在这里我如何区分struct Bstruct A::struct B

Jab*_*cky 6

#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;
}
Run Code Online (Sandbox Code Playgroud)

工作样本:

#include <stdio.h>

struct A
{
  int b;
  struct B { int a; };
};

int main() {
  printf("%d | %d", sizeof(struct A), sizeof(struct B));
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

32位系统上可能的输出:

8 | 4
Run Code Online (Sandbox Code Playgroud)

  • @cse符合标准的C编译器不能编译它:看[这里](https://www.godbolt.org/z/uLBQx-).但是在C++中它编译.这是gnu C扩展.阅读:/sf/answers/1727983841/ (2认同)
  • @cse - "验证_if C编译器是否支持内部结构_,....":您无法通过在C中运行代码来验证编译器是否支持某些内容.您需要诉诸文档,因为未定义的行为可能包括外观工作代码.在这种情况下,虽然C中支持_nested_结构,但[空结构不会导致未定义的行为](https://port70.net/~nsz/c/c11/n1570.html#6.7.2.1p8). (2认同)