clinuxpointersstructmember-access

de-referencing pointer using with &->


I have simple the nested structure:

struct abc {
        int i;
};

struct milan {
        struct abc obj;
};

int main()
{
    struct milan *ptr; 
    ptr = malloc(sizeof(struct milan)); 
    ptr->obj.i = 10;    
    printf("%d\n", ptr->obj); 
} 

It prints 10, but how the de-reference a pointer taking place here, is ptr->obj the same as &->obj == *obj ?


Solution

  • The expression ptr->obj is the same as ( *ptr ).obj.

    From the C Standard (6.5.2.3 Structure and union members)

    4 A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points, and is an lvalue.96) If the first expression is a pointer to a qualified type, the result has the so-qualified version of the type of the designated member

    and

    3 A postfix expression followed by the . operator and an identifier designates a member of a structure or union object. The value is that of the named member,95) and is an lvalue if the first expression is an lvalue. If the first expression has qualified type, the result has the so-qualified version of the type of the designated member.