通过引用传递在试图实现一个功能,改变菜单上的状态不工作

问题描述:

,但我的基准丢失struct菜单通过引用传递在试图实现一个功能,改变菜单上的状态不工作

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

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

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

  • 传中cnsle
  • 传递一个参考cnsle->currentState(即改变方法签名Menu ** itemptr和呼叫参数&cnsle->currentState
  • 或返回新值从gotoLowerLevel并为它分配:cnsle->currentState = gotoLowerLevel(cnsle->currentState)

我的选择将是最后的选择,因为读取调用代码,当这清楚可能会被修改。

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

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

/* .... */ 
cnsle->currentState = gotoLowerlevel(cnsle->currentState); 
+0

您可能还想检查NULL –

您正在按值传递指针。在对象上

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

您可能想要使用指向指针的指针。