如何为在main()外部或内部声明的变量分配内存 [英] How memory is allocated for a variable declared outside vs inside main()

查看:110
本文介绍了如何为在main()外部或内部声明的变量分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在使用一些大型数组(例如1000乘以1000的两倍)时,如果我在main()内声明该数组,我的程序就会用完内存,但是如果我在main()之外声明该数组,这似乎永远不会发生),甚至适用于更大的数组.有人可以解释一下区别是什么吗?

I have noticed when working with some large arrays (like doubles 1000 by 1000) that my program runs out of memory if I declare the array inside of main() but this never seems to happen if I declare the array outside main() even for larger arrays. Can someone explain what the distinction is?

推荐答案

在函数内部声明变量(在您的情况下为main)时,该变量将分配在堆栈上,并且如果变量太大(例如,大数组),您会遇到堆栈溢出.

When a variable is declared inside a function (in your case, main), it's allocated on the stack, and if it's too large (e.g, a big array), you'll encounter stack overflow.

在所有函数外部定义的变量是静态分配的.它的生命周期一直持续到程序终止.

A variable defined outside all functions is allocated statically. Its lifetime lasts until the program terminates.

这篇关于如何为在main()外部或内部声明的变量分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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