Lyesmith Lyesmith - 1 year ago 118
C Question

How to create an empty stack?

I'm trying to create a stack where I can push integers into it. So far I have this:

#include <stdio.h>
#define N 20

typedef struct {
int data[N]; // array of at most size N
// N should be a constant declared globally
int top;
} stack_t;

void push(stack_t *stack, int element);

int main(){

void push(stack_t *stack, int n) {
if (stack->top == N - 1) {
printf("Warning: Stack is full, You can't add'\n");
} else {
stack->data[++stack->top] = n;

stack_t * e_stack; // Empty stack created
push(e_stack, 2);


However, this code gives a runtime error. I assume it's because this part is wrong:
stack_t * e_stack; // Empty stack created

(That probably didn't create an empty stack)

But I know how is it wrong

Answer Source

You're right, all you've done is created a pointer that points at...something, but probably not a stack_t. You need to allocate something to point at. See malloc. Then you'll need to initialize stack_t::top to -1 or some other value. Zero probably won't work here since that index would likely be the first item in the stack.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download