Search code examples
c++stackgarbage

Stack function supposed to return a specified element, instead returns garbage value


int getElement(stack<int> s,int i){
if(i>1){
   s.pop();
   getElement(s,i-1);
   }
else
    return  s.top();
}

int main(){
    stack<int> pancakes;
    pancakes.push(1);
    pancakes.push(2);
    pancakes.push(3);
    printf("%d",getElement(pancakes,2));


 }

Help! My getElement function returns the element at i where i starts from the top value of the stack with the value of 1.

When I run getElement(2), it should return 2 on a stack: 3 - index 1, 2 - index 2 and 1 - index 3

it prints garbage value. Assume it only accepts values that are acceptable (index is within bounds), error handling is something I'll do later.


Solution

  • You are missing a return statement.

    Change

    int getElement(stack<int> s,int i){
    if(i!=1){
       s.pop();
       getElement(s,i-1);
       }
    else
        return  s.top();
    }
    

    to

    int getElement(stack<int> s,int i){
    if(i!=1){
       s.pop();
       return getElement(s,i-1); // The line with the missing return.
       }
    else
        return  s.top();
    }