1

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.(Which 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?

2
  • 'some_var->a[0]->b' should be 'some_var->a[0].b' Commented Feb 17, 2011 at 5:43
  • @Keith You're using the wrong character for the code. It's a "Grave Accent" ```. Commented Feb 17, 2011 at 5:54

3 Answers 3

8

Is some_var->a->b equivalent to some_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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes i actually meant to write some_Var->a[0].b , i meant to ask are the two equivalent? Yes thanks for your reply,just the confirmation i needed!
-1

Assuming that you have allocated memory for some_var, its safe to do some_var->a->b (as arrays decay into pointer).

1 Comment

Yes memory for some_var is allocated. OK thanks a ton,i just needed that confirmation
-1

Yes, _var->a[0]->b and _var->a->b are equivalent

Because a[0] and a is representing the base address of the structure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.