J's Study log

[C++] new & delete 본문

Computer Language/C++

[C++] new & delete

정우섭 2020. 2. 22. 20:44

new

 

1
2
int *ptr = new int;
int *arr = new int[10];
 

 

new is a keyword that replaces malloc() in C++.

(Of course you can use malloc(), if you need.)

Disadvantage in using malloc() is that you must allocate memory in size of bytes.

And you need proper casting ,because it's default return type is void.

 

1
2
3
4
int *ptr = new int;
int &ref = *ptr;
ref=20
cout<<*ptr<<endl;  //result : 20 
 

This sentence is meaningful, because it accesses heap area without pointer.

 

 

 

 

 

 

delete

1
2
delete ptr;
delete []arr;
 

delete is a keyword that replaces free() in C++.

If you delete 'arr' without '[]' only the first element of array gets deleted.

 

 

 

 

 

 

 

 

 

 

Accessing heap memory

 

 

1
2
3
4
int *ptr=new int;
int &ref=*ptr;
ref=20;
cout<<*ptr<<end;
 

 

Now you now how to access heap memory with reference as you see.

'Computer Language > C++' 카테고리의 다른 글

[C++] Inheritance  (0) 2020.03.10
[C++] Class / Struct  (0) 2020.03.08
[C++] Different length of String - not  (0) 2020.02.20
[C++] const  (0) 2020.02.08
[C++] Overloading, Default value  (0) 2020.02.08
Comments