C++ 通过指针初始化的字段有问题

C++ 通过指针初始化的字段有问题,c++,pointers,member-function-pointers,C++,Pointers,Member Function Pointers,我的问题涉及以下功能: /*Adds the transaction to the head of the linked list attached to the account.*/ void Bank::Worker::UpdateTransactionHistory(int account_number, string transaction, Bank *our_bank_ptr) { transaction_node new_trans; new_trans.tran

我的问题涉及以下功能:

/*Adds the transaction to the head of the linked list attached to the account.*/
void Bank::Worker::UpdateTransactionHistory(int account_number, string transaction, Bank *our_bank_ptr) {

    transaction_node new_trans;
    new_trans.transaction = transaction;

    if (our_bank_ptr->accounts[account_number].head == nullptr) {   //If this is the first transaction
        our_bank_ptr->accounts[account_number].head = &new_trans;

    } else {    //If this isn't the first transaction, disconnect the account from its current transaction list, connect the new transaction to the account and then connect the old list to the new transaction.
        transaction_node temp;
        temp = *(our_bank_ptr->accounts[account_number].head);

        our_bank_ptr->accounts[account_number].head = &new_trans;

        new_trans.next = &temp;
    }

if (our_bank_ptr->accounts[account_number].head) //here the correct string is printed
            cout << our_bank_ptr->accounts[account_number].head->transaction;
}
/*将交易添加到附加到帐户的链接列表的标题*/
void Bank::Worker::UpdateTransactionHistory(整数帐号、字符串事务、银行*我们的银行\ptr){
交易节点新建交易;
新交易=交易;
如果(我们的银行\u ptr->accounts[账号].head==nullptr){//如果这是第一笔交易
我们的银行\u ptr->账户[账号].head=&new\u trans;
}else{//如果这不是第一笔交易,请断开帐户与其当前交易列表的连接,将新交易连接到帐户,然后将旧列表连接到新交易。
事务节点温度;
temp=*(我们的银行->账户[账户编号].head);
我们的银行\u ptr->账户[账号].head=&new\u trans;
新交易记录下一步=&temp;
}
if(我们的银行\u ptr->accounts[账户编号].head)//此处打印正确的字符串
cout accounts[账号]。head->transaction;
}
这意味着更新new_trans的交易字段,然后该字段链接到给定帐户的交易列表的其余部分。就在我从更新事务函数返回之前,我测试以确保字符串被正确添加。函数的最后一行是
cout accounts[账号].head->transaction,正确输出事务字符串

但是,当我从函数返回并立即调用完全相同的代码行时,编译器告诉我更新的函数的事务字段仍然未初始化。这是尽管它是作为指针传入的

见鬼!?我认为,如果我通过指针将信息传递给函数,那么在函数过程中我对该信息所做的任何事情都是永久的?我错过了什么

谢谢你的帮助


Adam

您正在将指针设置为指向局部变量(
new\u trans
)。一旦函数退出,该变量将被销毁,指针将悬空。因此,试图取消引用它会导致未定义的行为。在您的情况下,这当前表现为单元化打印。但它可以做其他任何事情


如果您需要那里的指针,并且需要它们指向持久值,那么您必须动态地分配这些值。但真正的问题是:您需要指针吗?

您正在将指针设置为指向局部变量(
new\u trans
)。一旦函数退出,该变量将被销毁,指针将悬空。因此,试图取消引用它会导致未定义的行为。在您的情况下,这当前表现为单元化打印。但它可以做其他任何事情


如果您需要那里的指针,并且需要它们指向持久值,那么您必须动态地分配这些值。但真正的问题是:你需要指针吗?

new\u trans.next=&temp
看起来非常错误,我认为应该是
new\u trans.next=temp…代码完全不知道指针和对象的生存期是什么-1@DieterLücking只是好奇:问坏代码怎么会变成一个坏问题?主要的问题是缺乏抽象。@Angew有一个错误的假设作为问题的基础,使得这个问题成为一个坏问题<代码>新交易下一步=&temp
看起来非常错误,我认为应该是
new\u trans.next=temp…代码完全不知道指针和对象的生存期是什么-1@DieterLücking只是好奇:问坏代码怎么会变成一个坏问题?主要的问题是缺乏抽象。@Angew有一个错误的假设作为问题的基础,使得这个问题成为一个坏问题!啊!!这很有道理,谢谢你的帮助。我可能不需要指针,但在这一点上(哈哈)我别无选择。最后期限迫在眉睫!啊!!这很有道理,谢谢你的帮助。我可能不需要指针,但在这一点上(哈哈)我别无选择。最后期限迫在眉睫!