truvaking
truvaking

Reputation: 51

Expression must have struct or union type

I'm trying to make a stack / linkedlist implementation in C with. I'm struggling on the pop function of a stack.

Here's what my stack/linkedlist implementation looks like :

// a cell
struct cell_s
{
  void *elem;
  struct cell_s *next;
};
typedef struct cell_s cell_t;

// the list is a pointer to the first cell
struct linkedlist_s
{
  struct cell_s *head;
  int len;
};
typedef struct linkedlist_s linkedlist_t;

Here's the pop function :

/**
 * Pop remove and return the head
 */
cell_t *pop(linkedlist_t *list)
{
    if ((*list).len == 0) {
        // we cannot pop an empty list
        return NULL;
    }
    else 
    {
        cell_t* tmp = (*list).head;
        (*list).head = (*list).head.next; // <-- error occurs here
        (*tmp).next = NULL;
        return tmp;
    }
}

I don't understand what I did wrong. (*list).head is a struct cell_s so I should be able to access the attribute next ? But compiler won't let me do it.

Thanks.

Upvotes: 1

Views: 7707

Answers (1)

dbush
dbush

Reputation: 223739

The head field is not a struct cell_s. It is a struct cell_s *, i.e. a pointer to struct cell_s. As such, you need to use the -> operator to dereference and access the member.

list->head = list->head->next;

Note also that ptr->field is easier to read than (*ptr).field.

Upvotes: 5

Related Questions