Home > Net >  The pointer changes the value of the address it points to
The pointer changes the value of the address it points to

Time:11-19

I would expect pFirst to always point to the same place in the address. However it looks like pFirst moves along with pCurrent even though the function only entered the Else statement once.

Note:code is creating a linked list .

void Push(T data) {
      _size;
    Data d = Data(data);
    if (_pCurrent != nullptr) _pCurrent->SetNext(&d);
    else _pFirst = &d;

    _pCurrent = &d;
}

CodePudding user response:

d is created locally, so it does not exist after the function is over. Debug error is a little bit strange, because the program initializes a new element at the same address, so I did not immediately understand exactly what is happening.

This is the working version:

void Push(const T data) {

Data*d = new Data(data);
  _size;
if (_pCurrent != nullptr)
    _pCurrent->_pNext = d;
else
    _pFirst = d;
   _pCurrent = d;

}

CodePudding user response:

Data should be a static variable. The code should be like this:

Data d;
void UpdateData(Data newData) {
    //Do something on d using newData;
}

void Push(T data) {
          _size;
        UpdateData(data);
        if (_pCurrent != nullptr)
            _pCurrent->_pNext = d;
        else
            _pFirst = d;
           _pCurrent = d;
    }
  • Related