Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: operator -> and * [closed]

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|)

like image 692
G.V. Avatar asked Sep 05 '26 05:09

G.V.


2 Answers

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);
like image 188
Vlad from Moscow Avatar answered Sep 07 '26 21:09

Vlad from Moscow


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

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

You are correct about (*x).y being the same as x->y

But that is not what you do in the code:

s.numbers.(*swag).description

Look at it like this:

when comparing s.numbers.swag->description to x->y

x is s.numbers.swag
y is description

so by simple substitution

x->y equivalent to (*x).y becomes (*s.numbers.swag).description
like image 35
Support Ukraine Avatar answered Sep 07 '26 22:09

Support Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!