c - Why do I need to use & to pass a pointer to a struct in this stack implementation -
this question has answer here:
in following program need pass argument function using &
-operator although expect pointer , function expecting pointer. why need this?
the program implements simple stack using linked lists , incomplete types in c
. here 3 necessary files:
stack.h
#ifndef stack_h #define stack_h #include <stdbool.h> struct stack { int number; struct stack *next; }; /* * declare pointer stack structure thereby making use of incomplete * types. clients pull in stack.h able declare variables of type * pstack pointers stack structures. */ typedef struct stack *pstack; bool is_empty(pstack *s); void make_empty(pstack *s); void push(pstack *s, int new_num); int pop(pstack *s); #endif /* stack_h */
stack.c
#include <stdio.h> #include <stdlib.h> #include "stack.h" bool is_empty(pstack *s) { return !s; } void make_empty(pstack *s) { if (!is_empty(s)) pop(s); } int pop(pstack *s) { struct stack *tmp; int i; if (is_empty(s)) { exit(exit_failure); } tmp = *s; = (*s)->number; *s = (*s)->next; free(tmp); return i; } void push(pstack *s, int new_num) { struct stack *new_node = malloc(sizeof(struct stack)); if (!new_node) { exit(exit_failure); } new_node->number = new_num; new_node->next = *s; *s = new_node; }
stackclient.c
#include <stdio.h> #include <stdlib.h> #include "stack.h" int main(void) { pstack s1; int n; push(&s1, 1); push(&s1, 2); n = pop(&s1); printf("popped %d s1\n", n); n = pop(&s1); printf("popped %d s1\n", n); exit(exit_success); }
again, thought using
typedef struct stack *pstack;
and later on in main()
pstack s1;
i'm declaring pointer linked list stack
, hence fine pass s1
push()
using
push(s1, 1);
but need use
push (&s1, 1);
why?
your functions declared take pstack*
argument, pointer pointer stack
struct. use pstack
. you'll need replace instances of (*s)
s
in implementations of functions.
edit: pointed out in comments, write (*s)
in function implementations , rely on behavior correctness, need keep argument pstack*
. conceptually, because stack variable (s1
) literally top of stack itself, , must modified push
, pop
.
Comments
Post a Comment