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;
}
DevC only compiles but doesnt run the code. OnlineGDB runs it but only prints the first test.
CodePudding user response:
This is because your variable STACK* st;
was never initialized properly.
Some Important Points:
- Don't assign
-1
to the length (top
),0
would be better STACK* st;
should be justSTACK st;
- Your function
void push(STACK* st, int newitem)
should be declared withstatic
linkage. - Write
st->top
- Pass
st
variable by reference to thepush()
function - Instead of using bare
return 0;
, usereturn EXIT_SUCCESS;
, which is defined in the header filestdlib.h
. - As your total
STACK_SIZE
is only50
so,int
will be sufficient. But as yourSTACK_SIZE
grows usesize_t
for your length(top
). - use
int main(void) { }
, instead ofint main() { }
- NOTE: If
STACK_SIZE
andtop
becomes equal means yourarray
is filled completely then further addition of data will lead to Undefined Behavior.
Final Code
#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 ref
return EXIT_SUCCESS;
}