首页 > 解决方案 > 如何正确地将带有变量地址的指针从函数传递到另一个接受引用的函数

问题描述

我遇到的问题是我在 main 中声明的指针指向从函数返回的变量的地址,后来我尝试在接受引用的函数中传递指针,但是值它现在已经消失并以某种方式被垃圾值所取代。请告诉我我做错了什么。

#include<iostream>

void  somthingwrong(int &x) //*takes in the pointers address* 
{
    std::cout << somfing << std::endl; //*supposed to print 5 but outputs a 
                                      // garbage value*
    return;
}

int& number()
{
    int g = 5;

    return g;
}

int main()
{   
    int *h = nullptr;  

    h = &number(); //*the pointer passed gets the value of 5*

    somthingwrong(*h); //*here in this function the value is somehow erased 
                       //and couts some garbage value*




    return (0);
}

标签: c++pointersreference

解决方案


推荐阅读