【发布时间】:2012-08-01 17:18:41
【问题描述】:
可能重复:
Pointer to local variable
Can a local variable's memory be accessed outside its scope?
我有一个有趣的问题。我有一个返回指针的读取函数:
char * myReadFunc() {
char r [10];
//some code that reads data into r.
return r;
}
现在,我调用此函数将信息分配给我拥有的一些变量:
char * s;
//Some code to specify where to read from.
s = myReadFunc();
这会产生我想要的结果。
但是,当我这样做时:
char * s1;
char * s2;
//Some code to specify where to read from.
s1 = myReadFunc();
//Some code to change the read location.
s2 = myReadFunc();
我得到了一些奇怪的结果。两者的数据相同,并且始终来自第二个指定的读取位置。
所以我尝试了一些替代代码:
char * s1;
char * s2;
//Some code to specify where to read from.
char r [10];
//some code that reads data into r. IDENTICAL to myReadFunc().
s1 = r;
//Some code to change the read location.
s2 = myReadFunc();
这段代码产生了我想要的结果(s1 有来自一个位置的数据,s2 有来自另一个位置的数据)。
所以,我的问题是,为什么后面的代码有效,而上面的代码却没有? 我的猜测是,我的函数不知何故被这两个变量取别名,并且由于它指向这两个变量,因此每次调用它时都会重新分配这两个变量。有人了解这种行为的全部原因吗?
【问题讨论】:
-
有很多类似的问题。
标签: c++ c function pointers methods