我无法理解size_1
变量如何计算size of
数据成员名称。有人可以解释一下(((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);
}
您可以查看此代码段(来自上面的代码):
/* Or, without a declared variable: */
size_1 = sizeof(((struct cheese_msgbuf*)0)->name);
printf("Using pointer: %d\n", size_1);
编译器可帮助您获取sizeof
struct cheese_msgbuf
数据成员name
,如下所示:
struct cheese_msgbuf* compiler_temp_pointer = ((struct cheese_msgbuf*)0);
size_t size = sizeof(compiler_temp_pointer->name);
希望这对您来说很清楚
您可能知道,sizeof
是一个返回特定C符号大小的运算符。它需要一个变量名或一个类型。如果变量名是数组名,则返回整个数组的大小(以字节为单位)。
但是没有“ direct”方法来获取结构字段的大小,所以这是您发现的窍门(我不得不说您的代码很容易解释):
/* Or, without a declared variable: */
size_1 = sizeof(((struct cheese_msgbuf*)0)->name);
((struct cheese_msgbuf*)0)
。我们只转换地址0
;我们不需要它是有效地址,我们只需要告诉编译器将其解释为指向(struct cheese_msgbuf*)
name
。我们只是以访问我们具有“真实”变量(例如var->name
)的方式访问该字段的方式进行访问。在这种情况下,我们只需访问((struct cheese_msgbuf*)0)->name
sizeof
运算符:sizeof(((struct cheese_msgbuf*)0)->name)
。它将解析为20