【发布时间】:2020-06-17 09:26:36
【问题描述】:
我无法理解size_1 变量如何计算数据成员名称的大小。有人能解释一下(((struct cheese_msgbuf*)0)->name);这条线的含义和作用吗?
#include<stdio.h>
struct cheese_msgbuf {
long mtype;
char name[20];
};
int main() {
/* calculate the size of the data to send: */
struct cheese_msgbuf mbuf;
int size;
int size_1;
size = sizeof(mbuf.name);
printf("Using just sizeof operator: %d\n", size);
/* Or, without a declared variable: */
size_1 = sizeof(((struct cheese_msgbuf*)0)->name);
printf("Using pointer: %d\n", size_1);
}
【问题讨论】:
-
这条语句
(struct cheese_msgbuf*)0将空指针转换为你的结构类型(struct cheese_msgbuf)。 -
sizeof 在编译期间而不是在运行时解决。因此,当您告诉编译器在地址 0 处有一个 cheese_msgbuf 类型的结构时,编译器会信任您。