Question

Let's say for a structure called Point with x, y and next; when do I write P.y and when P -> next because for this code:

typedef struct
{
    int x, y;
    struct Point *next;
} Point;

I cannot use P -> next nor can I try if (P == NULL).

  1. Can I have combination of P.x and P -> next?
  2. When must I use -> and when . ?
Was it helpful?

Solution

If P has type Point, then you always use ..

 Point p;
 p.next;

If P has type Point*, then you always use ->.

 Point* p
 p->next;

If you really want to use . in the latter case, you have to deference first.

Point *p;
(*p).next;

Only in the latter case, it makes sense to check p == NULL, because a pointer can be NULL but a structure generally is not.


Since next is itself declared as a pointer, then you should use -> for following the pointer to its next pointer.

Point p;
p.next->next; // Will only work if p.next is NOT NULL.

Point* p;
p->next->next; // Will only work if p->next is NOT NULL.

Update: To remove the warning, change your declaration to the following.

typedef struct Point
{
    int x, y;
    struct Point *next;
} Point;

The problem is that the outside declaration is using the typedef and not the struct's tag, while the inside is using struct Point. See this question for details about why you get this behavior.

OTHER TIPS

You use P->next when P is a pointer type Point*, and you use P.next when it's the actual struct of type Point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top