Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble dereferencing double pointer

Tags:

c

pointers

I'd like to implement a stack using a linked list.

In order to implement pop() for my stack, I have the caller pass a double pointer (pointer to a pointer) that (eventually) points to the top of my stack ( first entry in linked list ).

The reason why I'm doing it this way is because this way the caller can keep a static pointer to the stack.

My linked list element struct :

struct Element {
int value;
struct Element *next;
};

pop() implementation:

int pop (struct Element **stack) {
    int popped_value = *stack->value;
    *stack = *stack->next;
    return popped_value;
}

The issue I have is trying to dereference the double pointer **stack. This code generates the following error:

error: request for member ‘value’ in something not a structure
error: request for member ‘next’ in something not a structure

In my mind, either *stack->value or **stack.value should work to retrieve popped_value, but I get the identical error.

like image 962
CallMeRex Avatar asked Nov 23 '11 02:11

CallMeRex


1 Answers

-> has higher precedence than the dereference operator, so that's like trying to dereference stack->value since the -> gets done first, and * done second. You need to use parentheses:

int popped_value = (*stack)->value;
*stack = (*stack)->next;

Or, as wallyk suggested in the comments, dereference the argument to get a single pointer and use that:

struct Element *sip = *stack;
int popped_value = sip->value;
*stack = sip->next;
like image 166
Seth Carnegie Avatar answered Sep 30 '22 17:09

Seth Carnegie