jpen
jpen

Reputation: 2147

ANSI C - Superfluous struct definitions?

I saw this code in this .c file.

struct node {
  Item data;
  struct node *next;
};

struct stack_type {
  struct node *top;
};

What are the benefits of creating two structs when one would do?

Upvotes: 1

Views: 156

Answers (3)

smang
smang

Reputation: 1207

They are looking to implement a stack. Each node contains a pointer to the next node, but each node does not contain a pointer to the top of the stack. Only the stack struct will store the pointer to the top of the stack. If every node in the stack pointed to the top, each node would have to be modified for every push or pop. The unnecessary top pointer would also be a waste of memory.

Upvotes: 3

Roman Saveljev
Roman Saveljev

Reputation: 2594

This way they can highlight functions, which work on a stack as a whole. Prototype will expect an instance of struct stack_type - you will not (supposedly) pass struct node from the middle of the stack.

Upvotes: 2

Vaughn Cato
Vaughn Cato

Reputation: 64308

It may make the code clearer to distinguish between the whole stack and a single node.

Upvotes: 4

Related Questions