I just started learning C and the online book contained the exercise 'implement a stack'. So I did, but thought I'd put it here, because I still don't feel comfortable with pointers.
So here it is:
#include <stdlib.h>
#include <stdio.h>
struct StackItem {
struct StackItem *previous;
int value;
};
void stack_push(struct StackItem **current, int value) {
struct StackItem *tmp = malloc(sizeof(struct StackItem));
tmp->previous = *current;
tmp->value = value;
*current = tmp;
}
void stack_pop(struct StackItem **current) {
if ((*current)->previous != NULL) {
struct StackItem *tmp = (*current)->previous;
free(*current);
*current = tmp;
} else printf("%s\n", "Previous is NULL");
}
void stack_print(struct StackItem *current) {
printf("%d\n", current->value);
while (current->previous != NULL) {
current = current->previous;
printf("%d\n", current->value);
}
}
int main(int argc, char **argv) {
struct StackItem *current = malloc(sizeof(struct StackItem));
current->value = 2147483647;
current->previous = NULL;
char input[10];
int i = 0;
while (i < 10) {
puts("Enter integer value to add to the stack:");
gets(input);
char *end;
int newVal = (int)strtol(input, &end, 10);
if (*end != '\0') { puts("That was no integer value."); --i; }
else stack_push(¤t, newVal);
++i;
}
stack_print(current);
puts("Stack printed once.");
i = 0;
while (i < 10) {
stack_pop(¤t);
i++;
}
stack_print(current);
puts("Stack printed twice.");
return 0;
}
Is there anything wrong/not good (I mean two different things here) with this?