C與C++實現高維陣列的動態開闢(本部落格學習於51CTO 鮑松山 C++高階教程)
阿新 • • 發佈:2018-11-17
目錄
1.VS安裝記憶體洩漏檢測工具VLD
參考這篇部落格即可:https://blog.csdn.net/GZrhaunt/article/details/56839765
2.C語言下實現二維陣列的動態開闢
#include<iostream> #include<assert.h> #include<vld.h> using namespace std; #define Type int #define ROW 3 #define COL 4 Type** _Malloc(int row, int col) { Type **p = (Type**)malloc(sizeof(Type*)*row); for (int i = 0; i < row; i++) p[i] = (int*)malloc(sizeof(int)*COL); return p; } void _Assign(Type **p, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { p[i][j] = i + j; } } } void _Print(Type **p, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%d", p[i][j]); printf(" "); } printf("\n"); } } void _free(Type **p, int row) { for (int i = 0; i < row; i++) free(p[i]); free(p); } void main() { Type **p = _Malloc(ROW,COL); _Assign(p, ROW, COL); _Print(p, ROW, COL); _free(p, ROW); }
3.C++下實現二維陣列的動態開闢
方法1:
#include<iostream> #include<assert.h> #include<vld.h> using namespace std; #define Type int #define ROW 3 #define COL 4 Type** _New(int row, int col) { Type **p = new Type*[row]; for (int i = 0; i < row; i++) p[i] = (int*)malloc(sizeof(int)*COL); return p; } void _Assign(Type **p, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { p[i][j] = i + j; } } } void _Print(Type **p, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout<<p[i][j]<<" "; } cout << endl; } } void _Delete(Type **p, int row) { for (int i = 0; i < row; i++) delete []p[i] ; delete[]p; } void main() { Type **p = _New(ROW, COL); _Assign(p, ROW, COL); _Print(p, ROW, COL); _Delete(p, ROW); }
方法二:
#include<iostream> #include<assert.h> #include<vld.h> using namespace std; #define Type int #define ROW 3 #define COL 4 typedef Type(*Ar)[COL]; Ar _New() { Ar p = new Type[ROW][COL]; return p; } void _Assign(Ar p) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { p[i][j] = i + j; } } } void _Print(Ar p) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { cout<<p[i][j]<<" " ; } cout << endl; } } void _Delete(Ar p) { delete []p; } int main() { Ar p = _New(); _Assign(p); _Print(p); _Delete(p); return 0; }
4.C++下實現高維陣列的動態開闢
#include<iostream>
#include<assert.h>
#include<vld.h>
using namespace std;
#define Type int
#define ROW 3
#define COL 4
#define Z 3
typedef Type(*Ar)[ROW][COL];
Ar _New()
{
Ar p=new Type[Z][ROW][COL];
return p;
}
void _Assign(Ar p)
{
for (int i = 0; i < Z; i++)
{
for (int j = 0; j < ROW; j++)
{
for (int k = 0; k < COL; k++)
{
p[i][j][k] = i + j + k;
}
}
}
}
void _Print(Ar p)
{
for (int i = 0; i < Z; i++)
{
for (int j = 0; j < ROW; j++)
{
for (int k = 0; k < COL; k++)
{
cout<<p[i][j][k]<<" ";
}
}
cout << endl;
}
}
void _Delete(Ar p)
{
delete []p;
}
void main()
{
Ar p = _New();
_Assign(p);
_Print(p);
_Delete(p);
}