2 using namespace std;
3 #include<cstdlib>
4 #include<string>
5 #include<new>
6 //new 類型==>(類型*)malloc(sizeof(類型))
7
8 int main()
9 {
10 int* p = static_cast<int*>(malloc(sizeof(int)));
11 int* q = new int;//不保證是0
12 int* r = new int(888);
13 cout<< *q <<","<<*r<<endl;
14 int n;
15 cout<<"請輸入一個整數:";
16 cin>>n;
17 int* a = new(nothrow) int[n];//申請空間返回數組最開始地址,不保證清零
18 //用(nothrow)如果申請不成功返回指針爲NULL
19 if(NULL == a)
20 {
21 cout<<n*sizeof(int)<<"申請失敗"<<endl;
22 }
23 else
24 {
25 for(int i = 0;i<n;i++)
26 {
27 cout<<a[i]<<" ";
28 if(a[i])
29 {
30 cout<<flush;
31 char c;
32 cin>>c;
33 }
34 }
35 }
36 cout<<endl;
37
38 delete r;r = NULL;
39 delete q;q = NULL;
40 delete[] a;a = NULL;
41 free(p);//malloc申請的內存不要用delete p
42 return 0;
43 }