局部数组在功能之外也有作用域吗? [英] does local array has scope outside the function also?

查看:65
本文介绍了局部数组在功能之外也有作用域吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



提前谢谢.
我正在使用Visual Studio 2008并遇到一个小问题.我是C ++的初学者.请帮帮我:

问题:在下面的代码中,我创建了一个由10个元素组成的数组.根据我的理解,该数组将分配在函数的堆栈内存中.
每当我调用此函数堆栈时,该函数堆栈将在执行后形成并删除.
这样,"* arr"应该给出运行时错误或内存异常,因为届时堆栈将被删除.但是为什么我没有任何错误?

Hi,

Thanks in advance.
I am using visual studio 2008 and having a small problem. I am a beginner in C++. Please help me out:

Problem: In the following code I am creating an array of 10 elements. As per my understanding this array will be allocated on the stack memory of function.
Whenever I call this function stack will be formed and deleted after execution of it.
In this way "*arr" should give run time error or memory exception because stack would have deleted by then. But still I am not getting any error why?

int* ArrayCreate(void)
{
    int arr[10] = {1,2,3,4,5,6};
    return arr;
}



int main()
{
int * arr = ArrayCreate();
int i = * arr;
int j = *(++ arr);
}



int main()
{
int* arr = ArrayCreate();
int i = *arr;
int j = *(++arr);
}

推荐答案

不会以使引用使用无效的内存指针失败"的相同方式来删除"堆栈空间.取而代之的是,堆栈空间可供重用,并且在您下次调用函数时内容可能会更改.

同时,该内存仍然存在,可以被引用,并且应该被认为包含"Random Junk".实际上,它可能很好地包含了您期望的值,但是您应该认为这纯粹是偶然的,并且只是出于编译器/库/OS的想法,换句话说,您不能指望任何东西.
The stack space is not "deleted" in the same manner that would make the reference "fail with an invalid memory pointer". Instead, the stack space is available for re-use and the contents will probably change on your next call to a function.

In the meantime, the memory still exists, can be referenced, and should be considered to contain "Random Junk". In fact, it may very well contain the values that you expect but you should consider that as purely accidental and at the whim of the compiler / library / OS, in other words, nothing you can count on.


该数组一直存在直到被删除.您无法相信它的存在,但目前为止.换句话说,它所在的内存可以使用,但尚未使用,因此它返回的是您期望的值.但是,如果以后再使用它们,则值可能会更改.
The array exists until it is deleted. You can''t trust it to be there, but it is, for now. In other words, the memory it sits in, is available for use, but it''s not been used yet, so it is returning the values you expect. But, if you relied on them later, the values could change.


这篇关于局部数组在功能之外也有作用域吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆