In C ++, the usage of New is flexible. Here is a simple summary:
1. New () allocates a memory space of this type and initializes this variable with the value in parentheses;
2. New [] allocates n Memory Spaces of this type and uses the default constructor to initialize these variables;
# Include <iostream>
# Include <cstring>
Using namespace STD;
Int main (){
// Char * P = new char ("hello ");
// Error allocates a char (1 byte) space,
// Use "hello" for initialization. This is obviously incorrect.
Char * P = new char [6];
// P = "hello ";
// The string cannot be directly assigned to the pointer P, because:
// The pointer P points to the first character of the string.
// Strcpy
Strcpy (P, "hello ");
Cout <* P <Endl; // only outputs the first character of the string pointed to by P!
Cout <p <Endl; // output the string pointed to by P!
Delete [] P;
Return 0 ;}
Output result:
H
Hello
3. When the new operator is used to define a multi-dimensional array variable or array object, it generates a pointer to the first element of the array. The returned type retains all dimensions except the leftmost dimension. For example:
Int * P1 = new int [10];
Returns an int x pointer to an int *
INT (* P2) [10] = new int [2] [10];
A two-dimensional array is added, and the leftmost one [2] is removed, with int [10] Left. Therefore, a pointer int (*) pointing to a one-dimensional array such as int [10] is returned (*) [10].
INT (* P3) [2] [10] = new int [5] [2] [10]; new a three-dimensional array, remove the leftmost one [5], there is also int [2] [10], so a pointer to the two-dimensional array int [2] [10] type int (*) [2] [10] is returned.
# Include <iostream>
# Include <typeinfo>
Using namespace STD;
Int main (){
Int * A = new int [34];
Int * B = new int [];
INT (* C) [2] = new
Int [34] [2];
INT (* D) [2] = new int [] [2];
INT (* E) [2] [3] = new int [34] [2] [3];
INT (* f) [2] [3] = new int [] [2] [3];
A [0] = 1;
B [0] = 1; // runtime error, no memory allocated, B only acts as a pointer, used to point to the corresponding data
C [0] [0] = 1;
D [0] [0] = 1; // runtime error, no allocated memory, d only acts as a pointer, used to point to the corresponding data
E [0] [0] [0] = 1;
F [0] [0] [0] = 1; // runtime error, no memory allocated. F only acts as a pointer and is used to point to the corresponding data
Cout <typeid (a). Name () <Endl;
Cout <typeid (B). Name () <Endl;
Cout <typeid (c). Name () <Endl;
Cout <typeid (d). Name () <Endl;
Cout <typeid (e). Name () <Endl;
Cout <typeid (f). Name () <Endl;
Delete [] A; Delete [] B; Delete [] C;
Delete [] D; Delete [] E; Delete [] F;
}
Output result:
Int *
Int *
INT (*) [2]
INT (*) [2]
INT (*) [2] [3]
INT (*) [2] [3]