/*
길이 정보를 인자로 받아서, 해당 길이의 문자열 저장이 가능한 배열 생성, 해당 배열의 주소값 반환하는 함수
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char* makeStrAddr(int len) {
char* str = (char*)malloc(sizeof(char)*len); // heap영역에 입력크기만큼 메모리 공간을 할당받아서 시작 주소 return
return str;
}
int main()
{
char* str = makeStrAddr(20);
strcpy(str, "9 to 24 everyday.");
cout << str << endl;
free(str);
return 0;
}
int* ptr1 = new int;
double* ptr2 = new double;
int* arr1 = new int[3];
double* arr2 = new double[7];
delete ptr1;
delete ptr2;
delete []arr1;
delete []arr2;
ex)
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char* makeStrAddr(int len) {
// char* str = (char*)malloc(sizeof(char)*len); // heap영역에 입력크기만큼 메모리 공간을 할당받아서 시작 주소 return
char* str = new char[len];
return str;
}
int main()
{
char* str = makeStrAddr(20);
strcpy(str, "9 to 24 everyday.");
cout << str << endl;
// free(str);
delete []str;
return 0;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
class Simple {
public:
Simple()
{
cout << "I'm simple constructor!" << endl;
}
};
int main()
{
cout << "case 1: ";
Simple *sp1 = new Simple; // new 연산자 이용해서 heap 영역에 변수 할당
cout << "case 2: ";
Simple *sp2 = (Simple*)malloc(sizeof(Simple)*1); // malloc 함수 이용해서 heap 영역에 변수 할당
cout << endl << "end of main" << endl;
delete sp1;
free(sp2);
return 0;
}
-> Simple *sp1 = new Simple; 실행 결과로 I'm simple constructor!가 출력되었지만, Simple *sp2 = (Simple*)malloc(sizeof(simple)*1);의 결과는 나오지 않음.
new와 malloc 함수의 동작 방식에 차이 존재
int *ptr = new int;
int &ref = *ptr; // heap 영역에 할당된 변수에 대한 참조자 선언
ref = 20;
cout << *ptr << endl;
-> 출력 결과 : 20
/*
메모리 동적 할당: new - delete(C에서의 malloc-free)
자료형 포인터 = new 자료형(크기)
new는 생성자를 호출한다. 즉 new는 객체를 생성시킨다.
객체를 생성하기 위해서는 생성자 호출이 있어야 한다.
*/
#include <iostream>
using namespace std;
//C++ 스타일
int main()
{
int size;
int* pary;
//int* pn = new int; 힙영역에 int크기로 동적 할당을 받는다.
//delete pn;
cout << "크기>> ";
cin >> size;
pary = new int[size];
pary[0] = 1;
pary[1] = 2;
*(pary + 2) = 3;
cout << pary[0] << ", " << pary[1] << ", " << *(pary + 2) << endl;
delete[] pary;
return 0;
}
/*
new는 생성자 호출이 되므로 초기화 가능
생성자 - 객체를 생성, 초기화하는 특별한 메서드
*/
#include <iostream>
using namespace std;
int main()
{
int* parr;
parr = new int[3] {10, 20, 30}; // 이름없는 배열객체 생성하고 10, 20, 30으로 초기화
// parr = new int[3] = {10, 20, 30};
cout << parr[0] << ", " << parr[1] << ", " << parr[2] << endl;
delete[] parr;
return 0;
}