<分区>
Possible Duplicate:
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
有来自另一个位置的数据)。
所以,我的问题是,为什么后面的代码有效,而上面的代码却没有? 我猜我的函数以某种方式为这两个变量设置了别名,并且由于它指向这两个变量,所以每次调用时都会重新分配这两个变量。有谁了解这种行为的全部原因?