【发布时间】:2009-02-15 02:58:05
【问题描述】:
再次问候,再次感谢为第一个问题提供答案的所有人。以下代码已更新为包含每个分配的两个函数。
要查看原始问题,请点击here。
我非常确信这满足了任务的要求,但我再次非常感谢任何帮助。我是否适当地修改了删除语句?再次感谢。
#include<iostream>
#include<string>
int** createArray(int, int);
void deleteArray(int*[], int);
using namespace std;
int main()
{
int nRows;
int nColumns;
cout<<"Number of rows: ";
cin>>nRows;
cout<<"Number of columns: ";
cin>>nColumns;
int** ppInt = createArray(nRows, nColumns);
deleteArray(ppInt, nRows);
}
int** createArray(int nRows, int nColumns)
{
int** ppInt = new int*[nRows];
for (int nCount = 0; nCount < nRows; nCount++)
{
ppInt[nCount] = new int[nColumns];
}
return ppInt;
}
void deleteArray(int** nPointer, int nRows)
{
for (int nCount = 0; nCount < nRows; nCount++)
{
delete[] nPointer[nCount];
}
delete[] nPointer;
}
附:这是作业文档本身,以防万一:
(1) 设计并实现一个为二维整数数组分配内存的函数:该函数应该接受两个整数作为参数,一个为行数,一个为列数。您需要在此函数中使用“new”运算符。请记住,我们需要首先创建一个指针数组。然后,对于该数组中的每个指针,我们需要创建一个整数数组。这个函数应该返回一个指向二维整数数组的指针。
(2) 设计并实现一个函数来为这个二维数组释放内存:该函数应该有两个参数(一个指向二维整数数组的指针,另一个是数字数组中的行数)。在函数中,您应该使用“delete”运算符为这个二维数组取消分配内存。您应该首先删除每一行(整数数组),然后删除指针数组。
【问题讨论】: