Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to pointer to struct in C

Tags:

c

pointers

struct

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;
like image 287
Ginko Avatar asked Aug 08 '26 16:08

Ginko


1 Answers

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;
like image 149
Sourav Ghosh Avatar answered Aug 10 '26 08:08

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!