-7

I have to learn this by 10 am tomorrow for a final because I'm a procrastinator.

I know can all scold me if you like. What I have here is I have to understand pointers to understand linked lists and the one thing that boggles my mind when working with pointers is when -> is used.

From what I've googled, it changes what a variable points to?

This confuses me when there are lines in the example code my professor gave me, such as temp = temp->head in this code or when it states printf("%d", temp->num);

Can anyone please help explain this? Thank you in advance.

    #include <malloc.h>
    #include <stdio.h>
    #include <stdlib.h>

    struct node
    {
        int num;
        struct node *ptr;
    };

     typedef struct node NODE;

     int main()
     {
      NODE *head, *temp = 0, *first;
    int count = 0;
    int choice = 1;

    while(choice)
    {
        head = (NODE *)malloc(sizeof(NODE));

    printf("Enter the value: \n");
    scanf("%d", &head->num);

    if (first != 0)
    {
        temp->ptr = head;
        temp = head;
    }
    else
        first = temp = head;
    fflush(stdin);
    printf("Do you want to continue?");
    scanf("%d", &choice);
    }

    temp->ptr = 0;
    temp = first;
    printf("\nStatus of the linked list");

    while (temp != 0)
    {
        printf("%d->" temp->num);
    count++;
    temp = temp->ptr;
    }
    printf("NULL\n");
    printf("Number of entries in linked list %d", count);
    return 0;
    }
}
AMadmanTriumphs
  • 4,888
  • 3
  • 28
  • 44

1 Answers1

3

It dereferences a pointer to a structure, and access a member of the structure.

Take for example, from your code:

temp->ptr = head;

This is the same as

(*temp).ptr = head;

The "arrow" operator make it a little simpler.

There is some history behind the -> operator if you're curious.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621