[ create a new paste ] login | about

Link: http://codepad.org/bqrzroD1    [ raw code | output | fork ]

C, pasted on May 10:
#include <stdlib.h>
#include <stdio.h>

typedef struct {
	int size;
	int *stack_array;
}stack;

void newStack(stack *a) {
	a->size = 0;
	a->stack_array = malloc(sizeof(int) * 1); 
}

void push(stack *a, int x) {
	int *new_array = malloc(sizeof(int) * a->size);
	int i;
	for(i=0; i < a->size; i++) {
		new_array[i] = a->stack_array[i]; 
	}
	
	new_array[i] = x;
	
	a->stack_array = new_array;

	a->size += 1;
}

int pop(stack *a) {
	if(a->size <= 0) {
		printf("CALL POP() WITH FILLED STACK");
		exit(1);
	}
	int *new_array = malloc(sizeof(int) * (a->size)-1);
	int i;
	for(i=0; i < a->size-1; i++) {
		new_array[i] = a->stack_array[i];
	}
	
	int popped = a->stack_array[i];
	
	a->stack_array = new_array;
	a->size -= 1;	
	return popped;
}	

void printStack(stack *a) {
	int i;
	printf("{");
	for(i=0; i<a->size-1; i++) {
		printf("%d, ", (a->stack_array)[i]);
	}
	printf("%d}\n", (a->stack_array)[i]);
}

int main (void) {
	stack a;
	newStack(&a);

	int i = 0;
	for(i = 0; i<12; i++) {
		push(&a, i);
	}

	printStack(&a);

	return 0;
}


Output:
1
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}


Create a new paste based on this one


Comments: