指针局部变量 [英] Pointer to local variable
问题描述
我可能有不同的功能存取权限的任何局部变量?如果在使用,怎么样?
May I have any acces to local variable in different function? If may, 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());
}
片code以上的输出:
The output of the piece of code above:
65
4202656
我究竟做错了什么?什么是4202656的意思??
What am i doing wrong? What the "4202656" means??
我必须整个阵列复制的replaceNumberAndPrint()函数可以访问到它比第一次?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access to it more than first times?
推荐答案
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.
要c您需要或者声明数组中的生命足够长的时间(在例子中,主
功能)一个范围或分配它在解决您的$ C $堆。如果您分配它在堆上,你需要手动释放它,或者在C ++中使用RAII。
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) 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屋!