简体   繁体   English

指针改变它指向的地址的值

[英]The pointer changes the value of the address it points to

I would expect pFirst to always point to the same place in the address.我希望pFirst总是指向地址中的同一个地方。 However it looks like pFirst moves along with pCurrent even though the function only entered the Else statement once.然而,尽管 function 只输入了 Else 语句一次,但看起来pFirstpCurrent一起移动。

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

    _pCurrent = &d;
}

d is created locally so it does not exist after the function is over, Debug error is a littl bit strange,because the program initializes a new element at the same address so I did not immediately understand exactly what is happening. d 是在本地创建的,所以在 function 结束后它不存在,调试错误有点奇怪,因为程序在同一地址初始化了一个新元素,所以我没有立即明白到底发生了什么。 This is working version:这是工作版本:

void Push(T data) {
        ++_size;
        Data*d = new Data(data);
        if (_pCurrent != nullptr)
            _pCurrent->_pNext = d;
        else
            _pFirst = d;
           _pCurrent = d;
    }

Data should be a static variable, the code should be like this:数据应该是一个 static 变量,代码应该是这样的:

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM