Stack* helper (char val, int x, int y) {
Your indentation and whitespace are kind of funky; I recommend looking at what some popular open-source code on GitHub does, and trying to copy them as closely as possible. Or, just run your code through a formatter such as clang-format
.
Stack *helper(char val, int x, int y) {
This function is only ever used in one place, so why do you have it? Right now it's kind of unsafe, because helper
returns a Stack *
which:
If you inlined it into push
, you'd have a complete unit of work, without either of those dangerous sharp edges.
Look into proper library organization. You should have a .h
file that defines struct Stack
and declares push
and pop
, and a .c
file with the implementations.
You should probably name the functions something like stack_push
and stack_pop
, since push
and pop
are likely to be common names; e.g. you might later want to write a struct Queue
with a queue_push
and queue_pop
. This kind of "manual namespacing" is common in C libraries.
Of course push
shouldn't call printf
(there's no "I" in "TEAM" and there's no "printf" in "push data onto a stack").
In pop
's argument list, you use w
and h
where you meant x
and y
.
pop
has interesting behavior on an empty stack: it just returns without initializing *x
and *y
. This is a problem for the caller, because the caller doesn't have any indication that anything went wrong! You should probably make pop
return a bool
to indicate whether it was successful.
Compare a pointer for null with (top == NULL)
, not !top
. Clarity counts!
Here's an idea if you want to push yourself harder: Right now you're passing x
, y
, and value
as individual arguments to push
, and retrieving them individually from pop
. Package them up into a struct!
Here's the struct definitions and function declarations for a different stack implementation. Can you see how to implement these functions?
struct Data { int x, y, value; }; struct DataStack { struct Data data; struct DataStack *next; } struct DataStack *datastack_push(struct DataStack *, struct Data); struct DataStack *datastack_pop(struct DataStack *); struct Data datastack_top(const struct DataStack *); bool datastack_empty(const struct DataStack *);
x
andy
mean in the structure.\$\endgroup\$