3

I'm making stack implementation in C using pointers and struct. Push and crateStack functions work well (both of them create new element in memory). Anyway, pop function doesnt work and I dont know why, here is code of that function:

int pop(element **lastStackEl)
{
  int poppedValue = *lastStackEl->value;
  element *temp = *lastStackEl->prev;
  free(*lastStackEl);
  *lastStackEl=temp;
  return poppedValue;
}

And here is my struct:

typedef struct Element {
  int value;
  struct Element *prev;
} element;

The compiler's giving error in first and second line of pop function:

error: request for member 'value' in something not a structure or union
int poppedValue = *lastStackEl->value;

1 Answer 1

2

As per the operator precedence, the indirection (dereference) operator (*) comes later than member access operator (->). So, without an explicit parenthesis, your statement behaves like

int poppedValue = *(lastStackEl->value);

Now, lastStackEl being a pointer to pointer to element it cannot be used as the LHS of member access operator. That is what the error message is all about.

You need to derefence lastStackEl first (to get a element* type), and then, you can use the -> to access the member value. You should write

int poppedValue = (*lastStackEl)->value;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.