首页 > 解决方案 > 通过引用传递指针?

问题描述

**So recently i came up with a question in an interview it was based on pointers**
void fun(int *p){
    int q = 10;
    p = &q;
}
int main() {
    int r = 20;
    int *p = &r;
    fun(p);
     cout<<*p<<endl;
}

*我的问题是(1)证明内存分配的结果是如何发生的?(2)如何通过引用传递这个指针变量(我在void fun()的参数中写了*&p)当我这样做时我观察到p正在打印一个垃圾值,现在首先我认为可能很有趣有不同的内存分配,当它从 fun 函数中获取 q 的地址时,它的地址发生了变化,但是 main 函数中的地址指向了一些垃圾值,我说得对吗,请解释一下?

标签: c++pointers

解决方案


void fun(int *&p) {
    int q = 10;
               // here the object q began its existence
    p = &q;
               // here you pass the address of that object *out*
               // of the function, to the caller

               // here the object q ceases to exist
               // question: does anyone have now-invalid pointers that
               //    pointed to that object?
}

您当然会立即看到,是的,调用者fun有一个不指向有效对象的指针(不存在的对象根据定义是无效的)。这是未定义的行为。任何事情都有可能发生。

无论你观察到什么都和其他人观察到的一样好:)我可以让这段代码假装工作,或者假装在几乎任何编译器上都失败了——这只是以某种方式安排事情的问题。当然,这并没有使代码更有效,而且“工作”或“失败”的概念无论如何都是没有意义的:代码是无效的,就 C++ 而言,关于效果的讨论是无效的,因为出色地 :)


推荐阅读