For eg. I have an array of structs 'a' as below:
struct mystruct{
int b
int num;
};
struct bigger_struct {
struct my_struct a[10];
}
struct bigger_struct *some_var;
i know that the name of an array when used as a value implicitly refers to the address of the first element of the array.(Whic开发者_StackOverflow社区h is how the array subscript operator works at-least) Can i know do the other way around i.e if i do:
some_var->a->b
, it should be equivalent to some_var->a[0]->b
, am i right? I have tested this and it seems to work , but is this semantically 100% correct?
Is
some_var->a->b
equivalent tosome_var->a[0]->b
?
No, it is equivalent to some_var->a[0].b
.
The exact specification of the array-to-pointer conversion is actually quite straightforward:
Except when it is the operand of the
sizeof
operator or the unary&
operator, or is a string literal used to initialize an array, an expression that has type array of type is converted to an expression with type pointer to type that points to the initial element of the array object and is not an lvalue (C99 6.3.2.1).
some_var->a
has the type my_struct[10]
, which is an array type, and since it is not the operand of the sizeof
or unary &
operator and is not a string literal, it is converted to a pointer to the initial element of the array.
Assuming that you have allocated memory for some_var
, its safe to do some_var->a->b
(as arrays decay into pointer).
Yes, _var->a[0]->b
and _var->a->b
are equivalent
Because a[0]
and a is representing the base address of the structure.
精彩评论