0

Hello I have a problem with pointer on struct in a stack.

I have a stack of struct:

stack<Somethink*> stack1;

And i want to push and pop array of "Somethink"

void Search(Somethink* array_Somethink, int s, int d,) {

stack1.push(&(array_Somethink[s]));  // 

while (stack1.size() != 0) {
    int  i = 0;

    array_Somethink[i] = *(stack1.pop()); // this return a error
    i++;
   }
}

I hope someone can give me a tip, how to properly push and pop from this stack

Thank you :D

C-PROG
  • 113
  • 3
  • 12

2 Answers2

0

top will return a pointer to the struct and you are trying to assign it to an instance of the struct. Basically you are trying to assign a pointer to Somethink to a position in an array of Somethink's

perencia
  • 1,498
  • 3
  • 11
  • 19
0
void Search(Somethink* array_Somethink, int s, int d,) {

stack1.push(&(array_Somethink[s]));  // 

while (!stack1.empty()) {
    int  i = 0;

    array_Somethink[i] = *(stack1.top());
    stack1.pop();
    i++;
   }
}

My modified code assumes, you have "owning" pointers to the elements on the stack somewhere else. If that is not the case, you would end with memory leaks here, as the pointers in the stack become dangling objects (leaks).

In order to avoid the potential for memory leaks, here, it might be a good idea if you used std::shared_ptr<Somethink> instead of raw pointers. Then, your stack would become a std::stack< std:shared_ptr<Somethink> >.

For details on std::stack operations empty(),pop(),top(), see std::stack in the usual place.

There, you will find explanations such as this:

std::stack::top C++ Containers library std::stack reference top(); const_reference top() const; Returns reference to the top element in the stack. This is the most recently pushed element. This element will be removed on a call to pop(). Effectively calls c.back().

BitTickler
  • 10,905
  • 5
  • 32
  • 53