140831 ● value type and reference type

Source: Internet
Author: User

Stack and stack differences

When the computer allocates memory, the heap and stack areas are separated.

1. Heap: It is generally assigned and released by programmers to store strings and arrays.

2. STACK: used to store function parameter values and local variable values.

For ease of understanding, you can think of the heap as a warehouse, and the stack as a record and index of the warehouse.

Value Type and reference type

Value types include integer, numeric, Boolean, floating point, and custom struct. The value type is stored in the stack area of the memory.

The reference types include arrays and strings. The reference type is stored in the heap area of the memory.

 

1 static void Hello (string a) 2 {3 A = "hello"; 4 console. writeline ("2," + a); 5} 6 7 static void main (string [] ARGs) 8 {9 string n = "hello"; 10 console. writeline ("1," + n); 11 Hello (n); 12 console. writeline ("3," + n); 13 14}

 

We all know that the string is of the reference type, the address passing method, analysis of the above Code, for beginners, may think the output result is: 1, hello; 2, hello; 3, hello. But actually:

Why is the actual display different?

Analysis: the string is stored in the heap area of the memory. The string is actually a character array and the length of the array cannot be changed. Therefore, when you assign a value to the string variable, the computer creates a new string in the heap area and assigns the address to the variable. In row 3, when n = "hello" is defined, the string "hello" is created in the heap area, and the variable N is created in the stack area, N stores the address "hello" in the heap area. When the program runs on Row 3, the computer actually creates "hello" in the heap area and sends the address to the form parameter A of the stack area. During this process, the address "hello" is stored in stack area n.

 

 

  

140831 ● value type and reference type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.