Skip to content
Snippets Groups Projects
Commit a863042b authored by dario.genga's avatar dario.genga
Browse files

Add stack init and destroy

Also fixed some issues in the test file that were caused by the
initialization of a stack's pointer instead of a normal stack.
parent 6895c2b8
Branches
No related tags found
No related merge requests found
...@@ -7,7 +7,9 @@ ...@@ -7,7 +7,9 @@
#include <stdio.h> #include <stdio.h>
void stack_init(stack *s, int size) { void stack_init(stack *s, int size) {
s->data = malloc(size * sizeof(int));
s->size = size;
s->top = -1;
} }
bool stack_is_empty(stack s) { bool stack_is_empty(stack s) {
...@@ -29,5 +31,8 @@ void stack_peek(stack s, int *val) { ...@@ -29,5 +31,8 @@ void stack_peek(stack s, int *val) {
} }
void stack_destroy(stack *s) { void stack_destroy(stack *s) {
free(s->data);
s->data = NULL;
s->top = -1;
s->size = -1;
} }
...@@ -85,30 +85,30 @@ void test_stack_pop(stack *s, int *val) { ...@@ -85,30 +85,30 @@ void test_stack_pop(stack *s, int *val) {
} }
int main() { int main() {
stack *s, *non_empty_stack; stack s, non_empty_stack;
int size = 10, value_to_add = 7; int size = 10, value_to_add = 7;
int *val; int *val;
printf("Starting the tests...\n"); printf("Starting the tests...\n");
// Test init and destroy // Test init and destroy
test_stack_init(s, size); test_stack_init(&s, size);
test_stack_destroy(s); test_stack_destroy(&s);
// Reinitialization // Reinitialization
stack_init(s, size); stack_init(&s, size);
stack_init(non_empty_stack, 3); stack_init(&non_empty_stack, 3);
non_empty_stack->data[0] = 1; non_empty_stack.data[0] = 1;
non_empty_stack->top = non_empty_stack->data[0]; non_empty_stack.top = non_empty_stack.data[0];
// Test the other functions // Test the other functions
test_stack_is_empty(s); test_stack_is_empty(&s);
test_stack_is_not_empty(non_empty_stack); test_stack_is_not_empty(&non_empty_stack);
test_stack_peek(*s, val); test_stack_peek(s, val);
test_stack_push(s, value_to_add); test_stack_push(&s, value_to_add);
test_stack_pop(s, val); test_stack_pop(&s, val);
// Free the memory // Free the memory
stack_destroy(s); stack_destroy(&s);
stack_destroy(non_empty_stack); stack_destroy(&non_empty_stack);
// End the tests // End the tests
printf("The tests are completed and were successful !\n"); printf("The tests are completed and were successful !\n");
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment