如何取消引用指针地址?

问题描述 投票:-2回答:2

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

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。

c++ pointers
2个回答
1
投票

You never modify 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;
}

0
投票

如何取消引用指针地址?

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

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

附:除非output_1具有静态存储,否则它将具有不确定的值。当其地址传递给edge_detect时,在该行上访问不确定的值:

int theOutput = *output

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

© www.soinside.com 2019 - 2024. All rights reserved.