Home > Net >  derefrencing in linked list?
derefrencing in linked list?

Time:05-21

I'm learning C and saw this segment of code for creating a linked list :

typedef struct node {
    int val;
    struct node * next;
} node_t;

void print_list(node_t * head) {
    node_t * current = head;

    while (current != NULL) {
        printf("%d\n", current->val);
        current = current->next;
    }
}

My question is , if current is simply a pointer holding a memory address how can the -> operator be applied to it in current->val , expecting a decimal to be printed - printf("%d\n", current->val); ignoring the format specifier surely this , would print a memory address rather than a literal value , as it hans't been dereferenced , or is it the arrow operator that does the dereferencing?

CodePudding user response:

if current is simply a pointer holding a memory address

It is. Its declaration leaves no room for doubt.

how can the -> operator be applied to it in current->val ,

-> is an operator applicable (only) to objects having pointer-to-structure types.

expecting a decimal to be printed - printf("%d\n", current->val)

The result of an -> expression is the designated member of the pointed-to structure. The member itself, not a pointer to it. The expression (a)->b is exactly equivalent to (*(a)).b. So,

or is it the arrow operator that does the dereferencing?

Yes.

  • Related