You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C语言中结构体或联合体的sizeof操作需使用变量?

为什么sizeof直接用struct/union标签会编译报错?

这其实是C语言和C++在结构体/联合体类型名使用上的一个常见差异,也是很多刚接触C的开发者容易踩的坑~

问题根源

在标准C语言中,你定义的struct person里的person只是结构体的标签(tag),它本身并不是一个独立的类型名。要引用这个结构体类型,必须带上struct关键字;同理,union u_type的u_type是联合体标签,必须搭配union关键字使用。

而你提到的“用变量可以正常编译”,是因为变量是已经声明的标识符,sizeof作用于变量(本质是表达式)时,编译器可以直接识别变量的类型,不需要额外的关键字。

解决方法

你有两种方式修复这个编译错误:

方法1:在sizeof中显式添加struct/union关键字

修改后的代码如下:

struct person { int age; char *name; };
union u_type { int t_int; double t_double; };

int main(void) {
    printf("size of person is %d\n", sizeof(struct person));  // 加上struct关键字
    printf("size of u_type is %d\n", sizeof(union u_type));    // 加上union关键字
    return 0;
}

方法2:用typedef给类型定义别名

如果你不想每次都写struct/union,可以用typedef提前给类型起一个别名,这样就能直接用别名作为类型名:

typedef struct { int age; char *name; } person;  // 直接定义类型别名person
typedef union { int t_int; double t_double; } u_type;  // 定义类型别名u_type

int main(void) {
    printf("size of person is %d\n", sizeof(person));
    printf("size of u_type is %d\n", sizeof(u_type));
    return 0;
}

补充说明

你提到的《GNU C参考手册》说sizeof可以用于类型和表达式是完全正确的——但这里的“类型”在C语言中对于结构体/联合体来说,必须是struct person这种完整的类型写法,而不是单独的person标签。

如果是用GCC编译C代码(比如把文件后缀改成.cpp或者添加-std=c++11编译参数),单独写person是可以的,因为C允许直接用结构体标签作为类型名,这是两种语言的语法差异。

内容的提问来源于stack exchange,提问作者Linh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:22