Hi people:

Here is my problem:

Codes: (My program is in the exact order as being represented here)

void push1(CStack stk) {
  stk.push(1);
  }

int main(void) {
  CStack mystack;
  printf("Stack initially: ");
  mystack.print();
  push1(mystack);
}

As you may read from above, the push1() function does not work at all.
I overheard from someone that this can be due to the input argument of push1(), e.g. stk(of type CStack) is located in a memory location can not be accessed by push1().
Can anyone give me some more information on this please?

Many thanks

Edit:: Use code tags. This is a warning.- WoLfPaCk

Recommended Answers

All 4 Replies

You are passing the stk variable by value. You should pass it by reference if you want to update the original value after it is returned from the function. Try this

void push1(CStack& stk) {
  stk.push(1);
  }

int main(void) {
  CStack mystack;
  printf("Stack initially: ");
  mystack.print();
  push1(mystack);
  printf("Stack after the push: ");
  mystack.print();
}

thanks, wolf.
May I ask you for another favor?
Could you please explain it a bit more?
I mean, the difference between passing by value and passing by reference.

I know some basic knowledge about passing by reference.

Thanks

difference between passing by value and passing by reference.

When you pass a variable to a function by value, the function creates a local copy of that variable and acts upon it. The variable that you passed into the function is not changed. So after the function finishes it's operation the original variable's value remains unchanged.

When you pass by reference, the function does the processing on the original variable's memory location. So the changes that are done to the variable are saved even after the function returns after processing.

That just makes so much sense. Wolf.
Thank you a lot for this fast and consice reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.