【问题标题】:Passing by reference does not change the variable通过引用传递不会改变变量
【发布时间】:2012-02-14 20:11:49
【问题描述】:

我正在尝试实现一个函数来更改菜单的状态,但是当它离开该函数时我的引用丢失了:

void gotoLowerlevel(Menu *item)
{
    if (item->chld != 0x00) {
        item = item->chld;
    }
}

函数调用就是这样完成的(currentState是一个指向struct Menu的指针):

case ENTER:
    if (cnsle->inMenuFlag == 0)
    {
        cnsle->inMenuFlag = 1;
        cnsle->currentState = cnsle->root;
        gotoLowerlevel(cnsle->currentState);
        displayMenu(cnsle->currentState,&cnsle->display);
    }

我不知道为什么这不起作用。有什么想法吗?

【问题讨论】:

    标签: c pointers gcc


    【解决方案1】:

    gotoLowerLevel 中的item 是一个局部变量,即使它是对别处对象的引用。要修改cnsle->currentState,您需要:

    • 传入cnsle
    • 传入对cnsle->currentState的引用(即将方法签名更改为Menu ** itemptr,调用参数更改为&cnsle->currentState
    • 或从gotoLowerLevel返回新值并赋值:cnsle->currentState = gotoLowerLevel(cnsle->currentState)

    我的偏好是最后一个选项,因为这在阅读调用代码时清楚地表明currentState 可能会被修改。

    其他人已经解释了如何传递引用。我首选解决方案的代码是:

    Menu* gotoLowerlevel(Menu *item)
    {
        if (item->chld != 0x00) {
            item = item->chld;
        }
        return item;
    }
    
    /* .... */
    cnsle->currentState = gotoLowerlevel(cnsle->currentState);
    

    【讨论】:

    • 你可能还想检查 NULL
    【解决方案2】:

    您正在按值传递指针。

    对它所指向的对象的操作对外是可见的,但指针本身只是一个副本。

    您可能希望使用指向指针的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多