Search code examples
cpointersstructpostfix-operator

C: operator -> and *


On the following example:

typedef struct {
    const char *description;
    float value;
} swag;

typedef struct {
    swag *swag;
    const char *sequence;
} combination;

typedef struct {
    combination numbers;
    const char *make;
} safe;

int main()
{
    swag gold = {"GOLD!", 1000000.0};
    combination numbers = {&gold, "6502"};
    safe s = {numbers, "RAMACON250"};

    //Correct handling
    printf("Result: %s \n", s.numbers.swag->description);

    //Faulty handling
    // printf("Result: %s \n", s.numbers.(*swag).description);

    return 0;
}

the following line is correct in order to receive the "GOLD!"

printf("Result: %s \n", s.numbers.swag->description);

but why the following is not correct as the (*x).y is same as x->y

printf("Result: %s \n", s.numbers.(*swag).description);

I receive the following fault during compilation:

C:\main.c|26|error: expected identifier before '(' token|)


Solution

  • Just use

    printf("Result: %s \n", ( *s.numbers.swag).description);
    

    According to the C grammar the postfix expression . is defined the following way

    postfix-expression . identifier
    

    So you may write for example

    ( identifier1 ).identifier2
    

    but you may not write

    identifier1.( identifier2 )
    

    Returning to your program you could even write

    printf("Result: %s \n", ( *( ( ( s ).numbers ).swag ) ).description);