简体   繁体   中英

Pointer to pointer to struct in C

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM