本文介绍了变量声明和内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在局部变量声明过程中是否分配了内存.

I want to know whether memory is allocated during the local variable declaration process.

假设我在函数内部编写此代码 int a = 10; ,并分配了内存值10.

Suppose I write this code inside function, int a =10; memory is allocated and the value 10 is stored in that.

int a; 怎么样?这个声明语句会分配4个字节的内存吗?

What about int a; ? This declaration statement will it allocate 4 bytes of memory?

谢谢.

推荐答案

本地变量通常存储在堆栈中,因此确实为 int 分配了字节:

Local variables are usually stored on stack, so indeed bytes are allocated for int:

int a;

因为它只是使用默认值(0),所以它与以下内容相同:

Because it simply uses default value (0), so it is the same as:

int a = 0;

int 是一种值类型,因此在堆栈上存储其值.如果要创建具有引用类型的局部变量:

int is a value type, so on stack is stored its value. If you would create local variable with reference type:

SomeClass a;

然后在堆栈上将仅分配 reference (值为null,因为它是引用类型的默认值).有关更多信息,您可以参考此问题

Then on stack it would be allocated only reference (with value null, as it is default value for reference types). For more information you can refer this question

这篇关于变量声明和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:53
查看更多