'I'm trying to create a stack in c using structures but my push function doesn't work
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.
Solution 1:[1]
This is because your variable STACK* st; was never initialized properly.
Some Important Points:
- Don't assign
-1to the length (top),0would be better STACK* st;should be justSTACK st;- Your function
void push(STACK* st, int newitem)should be declared withstaticlinkage. - Write
st->top++ - Pass
stvariable by address to thepush()function - Instead of using bare
return 0;, usereturn EXIT_SUCCESS;, which is defined in the header filestdlib.h. - As your total
STACK_SIZEis only50so,intwill be sufficient. But as yourSTACK_SIZEgrows usesize_tfor your length(top). - use
int main(void) { }, instead ofint main() { } - NOTE: If
STACK_SIZEandtopbecomes equal means yourarrayis 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 address
return EXIT_SUCCESS;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
