I'm trying to create a stack in C using structures but the push()
function I wrote is acting strangely. I'm sure it is something obvious that I'm missing but I just couldn't figure out what.
#include <stdio.h>
#define STACK_SIZE 50
typedef struct stack
{
int top;
int items[STACK_SIZE];
}
STACK;
void push(STACK* st, int newitem)
{
st->top++;
st->items[st->top] = newitem;
printf("%d", st->items[st->top]);
}
int main()
{
int n = 1;
STACK* st;
printf("test 1\n");
st->top = -1;
push(st, n);
printf("test 2\n");
return 0;
}
DevCpp only compiles but doesn't execute the code. OnlineGDB runs it but only prints the first test.
This is because your variable STACK* st;
was never initialized properly.
-1
to the length (top
), 0
would be betterSTACK* st;
should be just STACK st;
void push(STACK* st, int newitem)
should be declared with static
linkage.st->top++
st
variable by address to the push()
functionreturn 0;
, use return EXIT_SUCCESS;
, which is defined in the header file stdlib.h
.STACK_SIZE
is only 50
so, int
will be sufficient. But as your STACK_SIZE
grows use size_t
for your length(top
).int main(void) { }
, instead of int main() { }
STACK_SIZE
and top
becomes equal means your array
is filled completely then further addition of data will lead to Undefined Behavior.#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 50
typedef struct stack
{
int top;
int items[STACK_SIZE];
}
STACK;
static void push(STACK* st, int newitem)
{
if(st->top == STACK_SIZE)
{
fprintf(stderr, "stack size reached maximum length\n");
exit(EXIT_FAILURE);
}
st->items[st->top++] = newitem;
printf("%d\n", st->items[st->top - 1]); // we added +1 to `top` in the above line
}
int main(void)
{
int n = 1;
STACK st;
printf("test 1\n");
st.top = 0;
push(&st, n); //pass by address
return EXIT_SUCCESS;
}