【发布时间】:2020-08-08 14:36:11
【问题描述】:
我创建了一个程序,通过使用 c++ 中的动态内存分配获取用户输入来构建二维数组。该程序已成功编译并正在运行,但仅创建小型二维数组(如大小为 2x2)。当我尝试创建更大尺寸的数组时,exe 程序在接受用户输入后停止,显示一个小窗口弹出显示“array.exe 已停止工作”。 请指导我找出问题所在。
{
int a,b,i,j;
cout << "how many columns do you want in array ? ";
cin >> a;
cout << "how many rows do you want in array ";
cin >> b;
int * * ptr = new int * [b];
for(i=0;i<a;i++){
ptr[i] = new int[i];
}
for(i=0;i<b;i++){
cout << "enter elements of row no. " << i+1 << endl;
for(j=0;j<a;j++){
cout << "enter element no. " << j+1 << endl;
cin >> ptr[i][j];
}
}
cout << "array completed.press enter to view the array" << endl;
_getch();
system("cls");
for(i=0;i<b;i++){
for(j=0;j<a;j++){
cout << ptr[i][j] << " ";
}
cout << "\n";
}
for(i=0;i<a;i++){
delete[] ptr[i];
}
delete[] ptr;
return 0;
}
【问题讨论】:
-
“ptr[i] = new int[i];”应该是“ptr[i] = new int[a];”并且封闭循环应该从 0 到 b。
标签: c++ multidimensional-array dynamic-memory-allocation