0

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.

NotNando
  • 41
  • 4
  • [In C you should not cast the result of `malloc` and family](http://stackoverflow.com/a/605858/440558). Also build with more warnings enabled, warnings are often a sign of something "weird" you're doing. – Some programmer dude Mar 19 '14 at 10:47
  • Also, learn how to use a debugger. If the program crashes (which it seems to do) then running your program in a debugger will stop at the place of the crash. You can then examine (and more importantly) walk up the function call stack, as well as examine values of variables. – Some programmer dude Mar 19 '14 at 10:49
  • The `push` seems fine, at least to me. It should not produce your observed results. If anything I would suspect something with reading the input and executing `push` more than expected. You could try printing numerical value of the pushed character to see if you are getting anything weird like white-spaces etc. – luk32 Mar 19 '14 at 10:52
  • See [this](http://stackoverflow.com/q/12544068/2802841). Your every other `getchar()` most likely automatically gets a newline and thus appears to skip, that's why your program only waits for input 5 times instead of 10. – user2802841 Mar 19 '14 at 10:52
  • 1
    the push function looks fine; can you edit the post to include the printf and the output you are getting; it's difficult to get a feel of the problem with what you provided. – Pandrei Mar 19 '14 at 10:52

0 Answers0