標籤:iostream 圖片 ++ mes fclose 數組 fgetc 釋放 turn
分別用指標數組和二維數組產生二維空間,儲存資料並釋放。比如,資料如下:
//使用了下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 == ‘\n‘ || ch == EOF)21 break;22 buf[i][j] = ch;23 }24 buf[i][j] = ‘\0‘;25 }26 27 for(i = 0;i<3;i++)28 {29 cout<<buf[i]<<endl;30 }31 delete []buf;32 fclose(fp);33 #endif34 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 == ‘\n‘ || ch == EOF)47 break;48 buf[i][j] = ch;49 }50 buf[i][j] = ‘\0‘;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 #endif62 return 0;63 }
71. C++ 分別用指標數組和二維數組產生二維空間,儲存資料並釋放。 練習new/delete, new[]/delete[]