71. C++ 分别用指针数组和二维数组生成二维空间,存储数据并释放。 练习new/delete, new[]/delete[]

  分别用指针数组和二维数组生成二维空间,存储数据并释放。比如,数据如下: 

//使用了下fgetc()

 1 #include <iostream>
 2 #include <stdio.h>
 3 using namespace std;
 4 
 5 
 6 int main()
 7 {
 8 #if 0 //生成二维数组存储
 9     FILE* fp = fopen("G:\qtcode\temp.txt","r");
10 
11     //char buf[3][10] ={0};
12     char (*buf)[10] = new char[3][10];
13 
14     int i,j,ch;
15     for(i = 0;i<3;i++)
16     {
17         for(j = 0;j<8;j++)
18         {
19             ch = fgetc(fp);
20             if(ch == '
' || ch == EOF)
21                 break;
22             buf[i][j] = ch;
23         }
24         buf[i][j] = '';
25     }
26 
27     for(i = 0;i<3;i++)
28     {
29        cout<<buf[i]<<endl;
30     }
31     delete []buf;
32     fclose(fp);
33 #endif
34 
35 #if 1 //生成指针数组存储
36     FILE* fp = fopen("G:\qtcode\temp.txt","r");
37 
38     char **buf = new char*[3];
39     int i,j,ch;
40     for(i = 0;i<3;i++)
41     {
42         *(buf+i) = new char[8] ;
43         for(j = 0;j<8;j++)
44         {
45             ch = fgetc(fp);
46             if(ch == '
' || ch == EOF)
47                 break;
48             buf[i][j] = ch;
49         }
50         buf[i][j] = '';
51     }
52     for(i = 0;i<3;i++)
53     {
54        cout<<buf[i]<<"***"<<endl;
55        delete [](*(buf+i));
56     //   delete[] (buf[i]);
57     }
58     delete []buf;
59     fclose(fp);
60 
61 #endif
62     return 0;
63 }
原文地址:https://www.cnblogs.com/ZhuLuoJiGongYuan/p/9592048.html