箭头运算符位置C
使用此示例结构:箭头运算符位置C,c,struct,dereference,C,Struct,Dereference,使用此示例结构: typedef struct { uint8_t ary[2]; uint32_t val; }test_t; 这两个代码段在功能上是等效的: 剪1(支架尺寸内的箭头操作): 剪断2(支架尺寸外的箭头操作): 如果ary的大小改变,两者都报告正确的值,但是我不理解外括号示例的工作原理: sizeof((test_t *)0) // Using memory address 0 as pointer to test_t. size of pointer shou
typedef struct
{
uint8_t ary[2];
uint32_t val;
}test_t;
这两个代码段在功能上是等效的:
剪1(支架尺寸内的箭头操作):
剪断2(支架尺寸外的箭头操作):
如果ary的大小改变,两者都报告正确的值,但是我不理解外括号示例的工作原理:
sizeof((test_t *)0) // Using memory address 0 as pointer to test_t. size of pointer should be 4 on 32 bit system
因此,snip 2中的外部箭头操作应等同于:
4->ary or *4.ary
那么,为什么snip2的编译和运行方式与snip1相同呢
Expected output: 2
引用6.5.3一元运算符:
如您所见,接受表达式的sizeof
运算符不需要括号
因此,sizeof(((test_t*)0)->ari)
和sizeof((test_t*)0)->ari都是有效的
请注意,printf(“\n%d”,sizeof(((test_t*)0)->ari))代码>无效(调用未定义的行为),因为使用了错误的格式说明符<代码>%d
用于打印int
sizeof
operator返回size\t
,格式说明符是%zu
额外的括号是多余的,没有任何效果。有趣的是sizeof((test\t*)0)->ary
如何工作。是的,sizeof
是一个运算符,而不是一个函数。@KamilCuk:是的,以及如何sizeof(test\t*)0
没有:)。
4->ary or *4.ary
Expected output: 2
Syntax
1 unary-expression:
postfix-expression
++ unary-expression
-- unary-expression
unary-operator cast-expression
sizeof unary-expression
sizeof ( type-name )
_Alignof ( type-name )