可能重复:
指向局部变量的指针
可以在其范围之外访问局部变量的内存吗?
我有一个有趣的问题.我有一个返回指针的read函数:
char * myReadFunc() {
char r [10];
//some code that reads data into r.
return r;
}
Run Code Online (Sandbox Code Playgroud)
现在,我调用此函数将信息分配给我的一些变量:
char * s;
//Some code to specify where to read from.
s = myReadFunc();
Run Code Online (Sandbox Code Playgroud)
这会产生我想要的结果.
但是,当我这样做时:
char * s1;
char * s2;
//Some code to specify where to read from.
s1 = myReadFunc();
//Some code to change the read location.
s2 = myReadFunc();
Run Code Online (Sandbox Code Playgroud)
我得到一些奇怪的结果.两者的数据相同,并且始终来自第二个指定的读取位置.
所以我尝试了一些备用代码:
char * s1;
char * s2;
//Some code to specify where to read …Run Code Online (Sandbox Code Playgroud)