0

Possible Duplicate:
Why does the arrow (->) operator in C exist?

Why does C have both . and -> for addressing struct members?

Is it possible to have such modified language syntax, where we can take p as a pointer to struct and get a struct member's value just as p.value?

Community
  • 1
  • 1
  • The `->` is used to dereference pointers. – jweyrich Dec 06 '12 at 04:48
  • `ptr->member` is equiv to `(*ptr).member`, if that helps at all, and to answer your ending-question, No. – WhozCraig Dec 06 '12 at 04:57
  • See also http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c?lq=1 (for C++, but the answer is the same) – John Carter Dec 06 '12 at 05:00
  • OK, so -> is seems a kind of syntax sugar, but why it's still impossible to apply dot to pointer on a syntax level? –  Dec 06 '12 at 05:05
  • 3
    it happens to be a hot topic of last week. http://stackoverflow.com/questions/13366083/why-does-the-arrow-operator-in-c-exist – kennyzx Dec 06 '12 at 05:18

4 Answers4

3

From the C99 Spec.

The first operand of the . operator shall have a qualified or unqualified structure or union type, and the second operand shall name a member of that type.

The first operand of the -> operator shall have type pointer to qualified or unqualified structure or pointer to qualified or unqualified union, and the second operand shall name a member of the type pointed to.

My guess is, for identification purpose they used two operators for member access. i.e for pointer type struct variable is -> and . for ordinary struct variable.

For example:

struct sample E, *E1;

the expression (&E)->MOS is the same as E.MOS and
(*E1).MOS is the same as E1->MOS

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
3

You can think of p->m as shorthand for (*p).m

John Carter
  • 53,924
  • 26
  • 111
  • 144
2

Is it possible? Yes. The syntax is as follows:

(*ptr).member

The parentheses are required because the structure member operator . has higher precedence than the indirection operator *. But after using that a few times you will agree that the following is easier to use:

ptr->member

Why does C have both? Pointers to structures are used so often in C that a special operator was created, called the structure pointer operator ->. It's job is to more clearly and conveniently express pointers to structures.

Nocturno
  • 9,579
  • 5
  • 31
  • 39
0

. is for struct variable, and -> is for pointer. If p is a pointer, you can do p->value or (*p).value, they are same.

TieDad
  • 9,143
  • 5
  • 32
  • 58
  • OK, but what's wrong to have p.value in language syntax? –  Dec 06 '12 at 04:49
  • p.value only works when p is a struct variable. Compiler will check what p is. If p is a pointer, and you use p->value, then compile will give you error. – TieDad Dec 06 '12 at 04:50
  • it's not a _must_ that `.` should be used for "struct variable", there's unions. –  Dec 06 '12 at 04:56