Stacks

Hi, I've implemented a method to find a value from a 'Stack'. I just want to know that are there any logical errors or any kind of errors in this code?
Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
  bool about::findData(char key)
{
  if(top==-1)
    cout<<"Stack is Empty"<<endl;
  else
  {
    for(int x=0; x<maxSize-1; x++)
    {
       if(stackArray[x]==key)
          return stackArray[x];
    }
  }
}
The function should return the index, not the data value itself. In other words, return x, not return stackArray[x].
Hello LahiRulZ,

To expand on what Arslan7401 said the function is set up to return a bool, but you are trying to return the value at stackArray[index] and that will not work for what you want. The return value needs to match what stackArray was defined as.

Without testing the code I believe it should work, yet I do need to know more about top and maxSize to understand what they are.

Hope that helps,

Andy
You haven't shown the definition of stackArray, so it's hard to say.

One obvious problem: At line 9, you compare stackArray[x] to a char, so presumably stackArray[] is a char. At line 10, you return stackArray[x]. Since about::findData is a bool function, the char returned by stackArray[x] will be converted to a bool. So any non-zero value will be returned as true.

Line 7: Not clear if maxSize is the capacity of the stack (implied by the name), or the number of entries on the stack.

What is returned if top is -1? There is no return statement after line 12.
Topic archived. No new replies allowed.