文章提供三种实现方法,都通过验证
二维指针
指针数组
数组指针
#include <cstdlib>
#include <iostream>
using namespace std;
const int row = 4;
const int col = 5;
template <typename T>
void gen(T **array)
{
for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
{
array[i][j] = i + j;
}
return;
}
template <typename T>
void display(T **array)
{
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
return;
}
template <typename T>
void pointpoint(T ** &p)
{
p = new T*[row];
for(int i=0; i<row; i++)
{
p[i] = new T[col];
}
}
template <typename T>
void Rpointpoint(T ** &p)
{
for(int i=0; i<row; i++)
{
delete p[i];
p[i] = NULL;
}
delete p;
p = NULL;
}
template <typename T>
void pointarray(T *p)
{
p = new T*[row];
for(int i=0; i<row; i++)
{
p[i] = new T[col];
}
}
template <typename T>
void Rpointarray(T ** &p)
{
for(int i=0; i<row; i++)
{
delete p[i];
p[i] = NULL;
}
delete p;
p = NULL;
}
int main(int argc, char **argv)
{
/* 二维指针的实现 */
/*
int **p;
pointpoint(p);
gen(p);
display(p);
p[2][2] = 110
p[3][3] = 55;
display(p);
Rpointpoint(p);
*/
/* 指针数组的实现 */
/*
int *p[row]; // 指针数组的指针 , 也是个二维指针
for(int i=0; i<row; i++)
{
p[i] = new int[col]; // 多个分散的内存块
}
gen(p);
display(p);
p[2][2] = 110;
p[3][3] = 55;
display(p);
for(int i=0; i<row; i++)
{
delete p[i];
p[i] = NULL;
}
*/
/*
int *p[row]; // 指针数组的指针 , 也是个二维指针
int *tmp_p = new int[row * col];
for(int i=0; i<row; i++)
{
p[i] = tmp_p + i*col; // 一个分散的内存块
}
gen(p);
display(p);
p[2][2] = 110;
p[3][3] = 55;
display(p);
delete p[0];
*/
/* 数组指针的实现 */
int (*p)[col];
int *tmp_p = new int[row * col];
cout<<"Head:"<<tmp_p<<endl;
p = (int(*)[col]) tmp_p;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++) cout<<&p[i][j]<<" ";
cout<<endl;
}
p[2][2] = 110;
cout<< p[2][2] << endl;
delete (int*)p;
return 1;
}
./test
Head:0x502010
110
0x502010 0x502014 0x502018 0x50201c 0x502020
0x502024 0x502028 0x50202c 0x502030 0x502034
0x502038 0x50203c 0x502040 0x502044 0x502048
0x50204c 0x502050 0x502054 0x502058 0x50205c
本文详细介绍了使用C++实现二维数组与指针操作的三种方法:二维指针、指针数组、数组指针。通过具体代码示例展示了如何生成、显示、修改和释放内存资源。
3135

被折叠的 条评论
为什么被折叠?



