c++ - 通过引用传递指针?
问题描述
**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 函数中的地址指向了一些垃圾值,我说得对吗,请解释一下?
解决方案
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++ 而言,关于效果的讨论是无效的,因为出色地 :)
推荐阅读
- html - Jekyll 图片更新 - Github Chart
- typescript - Typescript,我很好奇它是否可以实现这种动态类型检查
- python - 如何在 Django 模型中将用户用作 ForeignKey
- c++ - 在功能块中使用新运算符时住在堆或堆栈上?
- node.js - 在 NodeJS + Typescript AWS Lambda 上进行单元测试
- python - 有没有办法递归地找到一组数字可以加起来为某个数字的不同方式?
- amazon-neptune - 无法在海王星工作台中使用 python 添加顶点
- fancybox - 使用新类型在按钮单击时更新 fancybox 当前幻灯片内容
- python - Python 三引号和百分比 (%) 语法
- javascript - 在第一次和第二次出现正斜杠之间替换字符串