-1

It is said that * operator in C means "Pointer to a variable", and following code is legal:

#include <stdio.h>
int main(){
    int a=5;
    int *p=&a;
    printf("%d\n", *p);
    return 0;
}

But the following code is illegal:

#include<stdio.h>

struct pair{
    int a,b;
};

int main(){
    struct  pair Alice, *Bob=&Alice;
    Alice.a=1;
    Alice.b=2;
    printf("%d %d\n",*Bob.a,*Bob.b);
    return 0;
}

So, why the * operator works fine for pointers to normal variables, but does not work for pointers to structures?

TJM
  • 709
  • 1
  • 6
  • 11
  • 6
    Postfix `.` has higher precedence than unary `*`. – EOF Jun 03 '16 at 16:20
  • This is probably what you're looking for http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c – Random Davis Jun 03 '16 at 16:21
  • It's not that it does not work, what you are saying does work, you are just getting the operator precedence wrong. – babon Jun 03 '16 at 16:34
  • `int *p` means "pointer to `int` **object**", no need to point to a variable. But here `*` is not an operator. As operator, it has a very different meaning. And variables can be structures, too. You confuse types and instances, variables, object, etc. Maybe you need as better C book. – too honest for this site Jun 03 '16 at 16:49

2 Answers2

5

Because member access operator . has higher precedence than indirection operator *.

You should use parentheses to access member of what is pointed without -> operator.

#include<stdio.h>

struct pair{
    int a,b;
};

int main(){
    struct  pair Alice, *Bob=&Alice;
    Alice.a=1;
    Alice.b=2;
    printf("%d %d\n",(*Bob).a,(*Bob).b);
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • You *need* to use parentheses if you're not going to use `->`. But you *should* use the `->` operator. – Keith Thompson Jun 03 '16 at 16:24
  • 1
    @KeithThompson: You avoid both parentheses *and* `->` by using `ptr[0].member`. – EOF Jun 03 '16 at 16:26
  • 1
    @EOF: You avoid obscurity by using `->`. Is there some reason that avoiding `->` is a good thing? – Keith Thompson Jun 03 '16 at 16:27
  • @KeithThompson: Sure, you should write readable code. But I find your assertion that parentheses are *required* when not using `->` to be incorrect. – EOF Jun 03 '16 at 16:28
  • @EOF: Ok, sure. The simplest and most obvious way to avoid `->` is to change `foo->bar` to `(*foo).bar`. But yes, there are other ways to avoid `->`. – Keith Thompson Jun 03 '16 at 18:58
2

Due to precedence of operators,you have to parenthesize your variable or alternatively use the -> operator:

#include<stdio.h>

struct pair {
    int a, b;
};

int main()
{
    struct  pair Alice, *Bob = &Alice;
    Alice.a = 1;
    Alice.b = 2;
    printf("%d %d\n", (*Bob).a, (*Bob).b);
    printf("%d %d\n", Bob->a, Bob->b);
    return 0;
}