【发布时间】:2022-01-10 19:38:02
【问题描述】:
我正在尝试制作一个二维数组,用户可以在其中输入数组可以采用的元素数量,以及数组中的元素。我想我设法创建了数组,但是当我尝试将一些元素放入其中时,例如 2x2 数组并将 2 作为其所有元素,我将其命名为 output。代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int rowCount,colCount;
cout<<"Enter the number of rows in Grid-Land:";
cin>>rowCount;
cout<<"Enter the number of columns in Grid-Land:";
cin>>colCount;
int** arr = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
arr[i] = new int[colCount];
cout<<"Enter the garbage amounts at the nodes of the MxN Grid-Land:"<<endl; //Elements of the array
for(int i=0; i<rowCount; i++){
for (int j=0; i<colCount; i++)
cin>>arr[i][j];
}
cout<<"\nThe 2-D Array is:\n";
for(int i=0;i<rowCount;i++){
for(int j=0;j<colCount;j++){
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
return 0;
}
【问题讨论】:
-
for (int j=0; i<colCount; i++)你不是说for (int j=0; j<colCount; j++)吗? -
查看您的
for循环。继续看他们,直到你看到你的错字。 -
有
new,但没有delete。闻起来像内存泄漏 -
就像@kmoser 提到的,内部循环显然是这里的根本原因