如何取消引用指针地址?

时间:2019-02-18 21:36:33

标签: c++ pointers

在变量参数之前,给我一个带有“&”的函数调用。不确定在构建实际功能时如何取消引用它们。

int state_1 = 1;
int input_1 = digitalRead(PIN_1);
int output_1;

edge_detect(input_1,&state_1,&output_1);


void edge_detect(int input, int* button_state, int* output) {
    int theOutput = *output
    int bState = *button_state;
    if (bState == 1 && input == 0){
       theOutput = 1;
       bState = 0;
    }
    else if (bState == 0 && input == 1){
       theOutput = -1;
       bState = 1;
    }
    else{
       theOutput = 0;
    }
}

当我打印到序列号时,最终结果似乎是output_1的5位数字地址。我希望output_1可以是1或0。

2 个答案:

答案 0 :(得分:1)

您从不修改output_1

这意味着您执行int output_1;时以其开头的任何垃圾值都将作为您打印的内容。这是未定义的行为。

您似乎要在edge_detect()中进行更改,因为您要传递指向它的指针,但是您只能修改其存储的整数的副本。要修改output_1本身的值,请将theOutput更改为引用:

int &theOutput = *output

或完全摆脱theOutput

//...
else if (bState == 0 && input == 1){
   *output = -1;
   bState = 1;
}
else{
   *output = 0;
}

答案 1 :(得分:0)

  

如何取消对指针地址的引用?

您可以使用间接操作符(即一元操作符*)通过指针进行间接操作(即取消引用)。像这样:

int o;         // object
int *ptr = &o; // pointer to the object
*ptr = 10;     // the pointer is indirected, and o is assigned

P.S。除非output_1具有静态存储,否则它将具有不确定的值。当其地址传递到edge_detect时,将在以下行中访问不确定的值:

int theOutput = *output

因此,该程序的行为将不确定。如果output_1具有静态存储空间,这不是问题,因为在这种情况下,其初始化为零。

相关问题