drakerc
drakerc

Reputation: 139

Stack push using external function

I'm trying to implement stacks using constructors in C++. I'm required to use an external function to push an element on the stack, however, it doesn't seem to work properly. The pushexternal function seems to "enter" the push function, but it doesn't increase the ind value, therefore it doesn't add a new element onto the stack (for example in my code, all pushxternals will try to push a value onto the same index, the last one used by s.push - ind==2). I'm not sure what I'm doing wrong.

Oh, I'm only supposed to modify the class code - the pushexternal and main have to remain unchanged.

#include <iostream>
using namespace std;

class Stack {
    public:
    int ind;
    int * arr;

Stack()
{
    arr = new int[25];
    ind = -1;
}
~Stack()
{
    delete [] arr;
}

void push(int val)
{
    arr[++ind] = val;
    cout << "Added " << arr[ind] << " to " << ind << endl;
}

void top()
{
    cout << "Last: " << arr[ind];
}
};

void pushexternal(Stack s, int a) {
    s.push(a);
}

int main() {
    Stack s;
    s.push(0);
    s.push(1);
    s.push(2);
    pushexternal(s, 3);
    pushexternal(s, 4);
    pushexternal(s, 5);
    return 0;
}

Results:

Added 0 to 0
Added 1 to 1
Added 2 to 2
Added 3 to 3
Added 4 to 3
Added 5 to 3
Top: 2

Upvotes: 2

Views: 112

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

void pushexternal(Stack s, int a) {
    s.push(a);
}

You are passing the Stack object to this function by value, not by reference. This makes a temporary copy of the original Stack object, so the original object remains unchanged. Not to mention that this will result in memory corruption, since the RAII principle has been violated.

Just by the luck of the draw, I guess, your code is not segfaulting.

Upvotes: 1

user4233758
user4233758

Reputation:

void pushexternal(Stack s, int a) {
    s.push(a);
}

receives a Stack as a parameter, which means it receives an object which is a copy of your object.

You should operate on references, this way you will not send a copy of the object to be manipulated, but the reference of the object, thus the original object will be manipulated.

Upvotes: 2

Related Questions