-
Dynamic memory allocation in C ++
-
C ++, dynamic memory allocation using the new keyword
-
C ++ dynamic memory allocation is performed based on the type of
-
delet keywords for memory release
. 1 . 1 // variable application 2 2 the Type = * pointer new new the Type; . 3 . 3 // .... . 4 . 4 Delete pointer; . 5 . 5 . 6 . 6 // array application . 7 . 7 the Type = * pointer new new the Type [N]; . 8 . 8 // .... 9 9 the Delete [] pointer;
10 #include " stdio.h " . 11 int main () 12 is { 13 is // new new initialization can 14 int * P = new new int ( 100 ); 15 // * P =. 5; 16 * * = P + P . 5 ; . 17 the printf ( " P = P% \ n- " , P); 18 is the printf ( " * D P =% \ n- " , * P); . 19 Delete P; 20 is P = new new int [ 10]; 21 is for ( int I = 0 ; I < 10 ; I ++ ) 22 is { 23 is P [I] = I + . 1 ; 24 the printf ( " P [% D] =% D \ n- " , I, P [I] ); 25 } 26 is Delete P; 27 return 0 ; 28 }
The result:
pi@raspberrypi:~ $ g++ main.cpp
pi@raspberrypi:~ $ ./a.out
p=0x15c4058
*p=105
p[0]=1
p[1]=2
p[2]=3
p[3]=4
p[4]=5
p[5]=6
p[6]=7
p[7]=8
p[8]=9
p[9]=10
-
The difference between the new keyword and malloc function
-
new keywords are part of C ++
-
malloc is a function provided by the C library
-
In particular new types of memory allocation units of
-
malloc byte memory allocation units
-
When applying a single type of new variables may be initialized
-
malloc do not have the memory initialization properties