如何使用指针从其他函数访问局部变量? [英] How to access a local variable from a different function using pointers?
问题描述
我可以在其他函数中访问局部变量吗?如果可以,怎么办?
May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
上面这段代码的输出:
65
4202656
我做错了什么? "4202656"是什么意思?
What am I doing wrong? What does the "4202656" mean?
我是否必须在replaceNumberAndPrint()
函数中复制整个数组才能比第一次访问更多?
Do I have to copy the whole array in the replaceNumberAndPrint()
function to be able to access it more than the first time?
推荐答案
myArray
是局部变量,因此,指针仅在其作用域的末尾才有效(在本例中为包含函数getArray
) 离开了.如果稍后访问它,则会出现不确定的行为.
myArray
is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray
) is left. If you access it later you get undefined behavior.
实际上,对printf
的调用会覆盖myArray
所使用的堆栈部分,然后包含其他一些数据.
In practice what happens is that the call to printf
overwrites the part of the stack used by myArray
and it then contains some other data.
要修复代码,您需要在寿命足够长的范围内声明数组(在示例中为main
函数)或在堆上分配它.如果您在堆上分配它,则需要手动释放它,或使用RAII在C ++中释放它.
To fix your code you need to either declare the array in a scope that lives long enough (the main
function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
我想念的另一种选择(如果数组不是太大,可能是最好的选择)是将数组包装到一个结构中,从而使其成为值类型.然后返回它会创建一个副本,该副本在函数返回后仍然有效.请参见 tp1 的答案有关此细节.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
这篇关于如何使用指针从其他函数访问局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!