【问题标题】:Trouble with fields initialized via pointer通过指针初始化的字段出现问题
【发布时间】:2013-10-29 14:39:48
【问题描述】:

我的问题涉及以下功能:

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

它意味着更新 new_trans 的交易字段,然后将其链接到给定帐户的交易列表的其余部分。就在我从更新事务函数返回之前,我测试以确保正确添加了字符串。函数的最后一行是cout &lt;&lt; our_bank_ptr-&gt;accounts[account_number].head-&gt;transaction;,正确输出交易字符串。

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

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

感谢您的帮助,

亚当

【问题讨论】:

  • new_trans.next = &amp;temp; 看起来很不对劲,我想说应该是new_trans.next = temp; ...
  • 代码完全不知道指针和对象的生命周期是-1!
  • @DieterLücking 只是好奇:询问糟糕的代码如何转化为糟糕的问题?
  • IMO 的主要问题是缺乏抽象。
  • @Angew 将错误的假设作为问题的基础会使问题成为一个坏问题!

标签: c++ pointers member-function-pointers


【解决方案1】:

您将指针设置为指向局部变量 (new_trans)。一旦函数退出,这个变量就会被销毁并且指针悬空。所以试图取消引用它会导致未定义的行为。在您的情况下,这目前表现为统一化的打印。但它可以做任何其他事情。

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

【讨论】:

  • 啊!有道理,谢谢你的帮助。我可能不需要指针,但在这一点上(哈哈)我别无选择。最后期限迫在眉睫!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多