【发布时间】:2019-02-11 20:17:18
【问题描述】:
我有以下代码sn-p:
#include <iostream>
#include <stdio.h>
void foo(int**p)
{
int y = 5; // memory for this is allocated, say at address 3000, and
// that position of memory is filled with the value 5
*p = &y; //we equal the value (contents) at address 2000 to 3000;
}
int main(int argc, char **argv)
{
int* p;
std::cout << &p << std::endl;
// p points to nowhere right now
foo(&p); //we pass p's address to foo()
printf("%d\n",*p);
std::cout << *p << std::endl;
}
当我运行此代码时, printf 输出 5 但 std::cout 打印无效数据。谁能解释一下为什么?
【问题讨论】:
-
y在foo()结束时超出范围,因此取消引用p是未定义的行为。 -
定义无效数据。你期待什么?
-
我不确定 "we equal the value (contents) at address 2000 to 3000;" 是什么意思,但听起来你认为
p现在包含该值5?如果是这样,请再次查看int**p并注意它有 2 个星号,因此*p是int*(一个指针)。 -
重要无关说明:
// p points to nowhere right now不正确。p指向某处,但由于它未初始化,您不一定知道它指向何处。您可能会看到它指向 null,因为堆栈在启动时被清零,但您不能指望这一点。 -
@Frank 不幸的是,如果除了上帝真的恨你之外没有其他原因,它可以指向一个有效的对象。剩下的就是争论语义。我坐在“指针会指向”阵营。
标签: c++