C vs C++
// C
int *p = (int *)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
p[i] = i;
free(p);
// C++
int *p = new int[N];
// or int &p = new int[N];
for (int i = 0; i < N; i++)
p[i] = i;
delete[] p;
N : 할당할 배열 개수.
Example
int *p = new int; // pi points to unintialized int
int *pi = new int(7); // which pi points has value 7
string *ps = new string("hello") // ps points "hello"
int *pia = new int[7]; // block of seven unintialized ints
int *pia = new int[7](); // block of seven ints value intialized to 0
string *psa = new string[5]; // block of 5 empty strings
string *psa = new string[5](); // block of 5 empty strings
int *pia = new int[5]{0,1,2,3,4}; // block of 5 ints intialized
string *psa = new string[2]{"a", "the" // block of 2 strings intialized
delete pi;
delete[] pia;
'C++ > C.S 필요한 C++ 문법!' 카테고리의 다른 글
[중요] C++ 0.06 - Reference Operator & (0) | 2021.10.26 |
---|---|
C++ 0.05 - Default Function Arguments (0) | 2021.10.26 |
C++ 0.04 - Inline functions (0) | 2021.10.26 |
C++ 0.03 - Input & Output (0) | 2021.10.25 |
C++ 0.02 - Namespaces (0) | 2021.10.25 |