c - 如何获取内部结构的大小

标签 c sizeof

我正在尝试获取内部结构的大小,即 struct B。但是我遇到了编译错误:

prog.c: In function ‘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;
}

你能建议我如何在 C 中实现这个吗?

已更新

来自 @Jabberwocky 的回答解决了我的上述问题。但是下面的代码呢?这也可以找到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;
}

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

prog.c:8:8: error: redefinition of ‘struct B’
struct B
^
prog.c:5:10: note: originally defined here
struct B{};
^
prog.c: In function ‘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

最佳答案

#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;
}

工作样本:

#include <stdio.h>

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

int main() {
  printf("%d | %d", sizeof(struct A), sizeof(struct B));
  return 0;
}

在 32 位系统上可能的输出:

8 | 4

关于c - 如何获取内部结构的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336530/

相关文章:

c - fgets 在提升为流的描述符中不阻塞

c++ - 如何获取传递给函数的数组的长度?

c# - x64 上的 sizeof(int)?

c - 程序没有在 scanf ("%c", &ch) 行停止,为什么?

c - 是否有任何支持负零或将其保留为陷阱表示的实现?

C语言中Sizeof运算符的复杂声明

c - 为 C 中的指针重新分配比最初更少的内存

c - short、int、long、float、double long、double、char 的大小

c - 使用相同的代码为 2 种语言生成文档

c - 我如何能够从另一个文件访问静态变量?