Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Push() problem with stack

  1. Sep 6, 2009 #1
    What's wrong with this piece of code:

    Code (Text):
    for (i=0; i!='\n'; i++)
            if (isdigit(elements[i]))
                array[i] = elements[i] - '0';
                push(mystack, array);
    Whever I run it, it gives exception. There's some problem in this line but I can't igure what is it:

    Code (Text):
    push(mystack, array);
    Here's the implementation of the push function:

    Code (Text):
    int push (stackADT stack, stack_elem_t elem)
        static int count;
        if (count == MAX_STACK_DEPTH-1)
           stack->stk = realloc(stack->stk,2*sizeof(struct stackCDT) );
            MAX_STACK_DEPTH = 2*sizeof(struct stackCDT);
        if (!stack) {
            return (ADT_INVALID_STACK);
        if (stack->stack_ptr == (MAX_STACK_DEPTH - 1)) {
            return (ADT_STACK_FULL);
        stack->stk[stack->stack_ptr] = elem;
        return (ADT_NOERROR);
    What's the problem?
  2. jcsd
  3. Sep 6, 2009 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    There are a couple things that worry me, but the most significant one is your for loop bounds. You're letting the integer i range over the numbers from zero up through the number '\n'? '\n' is indeed a number (13, I think), but that's surely not what you intended?
  4. Sep 6, 2009 #3
    End of line constant?
  5. Sep 6, 2009 #4
    I did run the code without the statement:

    Code (Text):
    push(mystack, array);
    and it didn't generate any exception. So i guess the problem exists in this line?
  6. Sep 6, 2009 #5
    More likely the problem is actually occurring in the push() function. I do not see anything wrong with the push() function (which it looks as if he copied from somewhere anyway). Perhaps something is wrong with the arguments to push(), causing push() to misbehave? Is it possible mystack needs to be (but has not been) initialized. I'd also expect this code to crash anytime elements is less than 13 items.

    Peon of the Beast: What was the exception? On what line did the exception occur? What is the type of mystack? What is "array"? And what is it you think this code is doing?
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook