Generation of structural class values
• A structural class variable exists in the stack
The dimensions field is not pre-assigned.
The values field can be read only after being assigned a value.
The vertex operator is used to access members.
The following example assumes that Pair is a structure with two public integer class members X, Y
Static void Main ()
{
Pair p;
Console. Write (p. X); // Error
...
}
Static void Main ()
{
Pair p;
P. X = 0;
Console. Write (p. X); // correct
...
}
Structural class variables exist in the stack. In the above example, although a Pair class structure variable called p is declared, it is only a short form of declaring two local variables p. X and p. Y.
The Console. Write of the first program in the preceding example tries to use the value of p. X, but it is incorrect because p. X is not assigned an initial value.
Structural class value Initialization
• A structure variable:
Can always use the default constructor for initialization.
The default constructor initializes the field to 0/false/null.
Static void Main ()
{
Pair p;
Console. Write (p. X); // error, p. X not initialized
...
}
Static void Main ()
{
Pair p = new Pair ();
Console. Write (p. X); // correct, p. X = 0
...
}
In addition to the initialization method described above, you can also use the default constructor to initialize a structure variable. The new keyword is always used to call the constructor. A structure variable is of the value type and directly exists in the stack. The use of the new keyword will not open up memory in the heap. The default constructor of the structure always initializes all fields in the structure variable (you cannot change this line as described in the following section ).
If you have a C ++ or Java background, it may be hard to believe that using the new keyword to call the constructor will not allocate memory in the heap, but this is the case in C. The structure variable exists in the stack. When the constructor is called to initialize its fields, no heap memory allocation occurs.
Note for C ++ programmers: brackets must be used to call the default constructor in C.
Pair p = new Pair; // Error
Pair p = new Pair (); // correct
Author: ershouyage