So I'm trying to implement a Stack in C and my push method seems to be making my loops in main run twice. What I mean is that I have:
int main(int argc, char *argv[]){
int i;
for(int i = 0; i < 10; i++)
push(getchar());
}
then I get to push 5 times before the program terminates. If I put a print statement in there, such as:
printf("i: %i ", i);
then I get myInput i=0 i=1 myInput
and so on.
The problem seems to be in my push method, but I'm not sure what's wrong with it. I'm new to malloc, so if the problem is obvious, I'm sorry. I can't figure out what's causing this though.
My code:
struct Node{
char c;
struct Node *nextNode;
};
struct Node *head = NULL;
char pop(){ ... }
int empty(){ ... }
void push(char ch){
struct Node *next = (struct Node *) malloc(sizeof(struct Node));
next->c = ch;
next->nextNode = head;
head = next;
}
I'm sure there are multiple problems here, but I'm not asking for a free code fix, I'm just trying to get this problem fixed.
Any tips or advice is deeply appreciated, and thank you in advance.
EDIT: user2802841 and luk32 are right, the way I was passing in the characters meant that the newline was consumed along with the actual characters, making it look like it was skipping. adding an extra getchar() to consume the newline solved the issue, thank you so much.