-1

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?

Exiatron00
  • 13
  • 2

1 Answers1

1

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • In your third remark, the extra parentheses do not improve the clarity. I suggest editing to: _The expression `a->b` is exactly equivalent to `(*a).b`_ – Wyck May 20 '22 at 13:29
  • if , say both a AND b are pointers would a -> b - equivelent to (*a).(*b)? – Exiatron00 May 20 '22 at 14:34
  • @Exiatron00: no, it would still be equivalent to `(*a).b`. – Mat May 20 '22 at 15:29