如何动态开辟二维空间的问题,

本文提供了一段C++代码示例,展示了如何动态分配内存创建一个二维整型数组,并对其进行初始化、遍历及释放内存的过程。通过此示例,读者可以了解C++中动态内存管理的基本方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你的问题其实就是如何动态开辟二维空间的问题, 这个问题在C++ 学习者中是每个人都会遇到的, 针对这个问题我写了一个 Demo code, 希望对你以及对大家会有一些帮助。
[CODE]
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int rows = 2;
int cols = 3;

// create a dynamic array
int ** array = NULL;
array = new int * [rows];


for(int i = 0; i < rows; i++)
{
array[i] = new int[cols];

// init this 2d array
for(int j = 0; j<cols; j++)
{
array[i][j] = (i+1)*(j+1);
}
}


// to check what we have done
for(int i = 0; i < rows; i++)
{
for(int j = 0; j<cols; j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}

// before you leave the program
// you should release the space what you have dynamically allocated
// to delete the allocation
for(int i = 0; i<rows; i++)
{
delete [] array[i];
array[i] = NULL; // to avoid wild pointer
}

delete [] array;
array = NULL; // to avoid wild pointer

system("pause");
return 0;
}

[/CODE]

http://bbs.bccn.net/thread-62318-1-1.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值