I'm new in c and trying to push int and string as memory address into stack but I don't understand how can I do that. Here is my code:
cout << "Filling stack..." << endl;
for (int i = 0; i < MULTIPLIER * STACK_SIZE; i ) {
if (stack.push(i 1)) {
cout << "pushed: " << i 1 << endl;
} else {
cout << "overflow error: " << i 1 << " not pushed" << endl;
}
}
and here my stack.cpp file where located my Stack class.
Stack::Stack() {
this -> top = -1;
}
Stack::~Stack() {
}
bool Stack::push(int x, const string* info ){
if (top < STACK_SIZE -1) {
stack[ top] = new Data;
stack[top] -> id = x;
stack[top] -> information = *info;
}
return true;
}
bool Stack::pop(struct Data *passData){
bool popped = false;
if (top > -1){
passData = stack[top--];
popped = true;
}
return popped;
}
bool Stack::peek(struct Data *passData){
bool popped = false;
if (top > -1){
passData = stack[top];
popped = true;
}
return popped;
}
bool Stack::isEmpty() {
return (top < 0);
}
CodePudding user response:
Your push function takes 2 arguments but you are providing only one, that's causing the error. Also I would advice you to use map or a custom class for the elements in the stack.
CodePudding user response:
Are you sure you have added all the parameters in your function call?
When that error happens, the cause is definetly the function call not having enough parameters. Keep that in mind when creating and calling your functions.
CodePudding user response:
The other answers I see are correct, but I'm going to spell this out a little more.
bool Stack::push(int x, const string* info ){
...
}
if (stack.push(i 1)) {
...
}
Your method takes two arguments, but you're only passing one. This is a problem.
Note however, that if you're using raw pointers in C , you're almost certainly doing something wrong. I would write it with a reference instead.
bool Stack::push(int x, const string & info ){
if (top < STACK_SIZE -1) {
stack[ top] = new Data;
stack[top] -> id = x;
stack[top] -> information = info;
}
return true;
}
This is subtle -- I changed the method signature very slightly plus I changed how I use it. That is, changed *
to &
in the method signature (also you'll do the same thing in your .h file), and then I removed &
where I used info.
This isn't C - you use pointers a LOT less in C . Use references instead.