gpt4 book ai didi

c++ - C++ 中的二维整数数组,每行元素数量为奇数

转载 作者:行者123 更新时间:2023-12-01 22:42:42 24 4
gpt4 key购买 nike

该数组的行数和列数由用户指定,但行数不相同(数组不均匀),并且用户将通过输入元素来填充数组。

这是我编写的代码,但是当我尝试获取用户的输入时,代码在获取一些输入后崩溃了。请您帮助我纠正我的代码并指出我的缺陷。谢谢。

#include <iostream>
//2d array
using namespace std;

int main()
{
int row;
int col_x;
cout << "Enter the row number:" << endl;
cin >> row;
//cout<<"Enter the column number:"<<endl;
//cin>>col;
int **a = new int *[row];
for (int r = 0; r < row; r++)
{
cout << "Enter the column no.of array " << r << endl;
cin >> col_x;
a[r] = new int[col_x];

cout << "Enter the elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cin >> a[i][j];
}
}
cout << "The elements in the array:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col_x; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}

delete[] a;
a = NULL;

return 0;
}

最佳答案

有一个额外的 for 循环。另外,您必须存储每行的大小。并对二维数组进行正确的释放。

#include <iostream>
//2d array
using namespace std;

int main()
{
int row;
cout<<"Enter the row number:"<<endl;
cin>>row;
int **a=new int *[row];
int *col_x = new int [row];

for(int r=0;r<row;r++){
cout<<"Enter the column no.of array "<<r<<endl;
cin>>col_x[r];
a[r]=new int[col_x[r]];

cout<<"Enter the elements in the array:"<<endl;

for(int j=0;j<col_x[r];j++){
cin>>a[r][j];
}
}

cout<<"The elements in the array:"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col_x[i];j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}

for (int i=0; i<row; ++i)
delete[] a[i];
delete []a;
delete []col_x;
return 0;
}

关于c++ - C++ 中的二维整数数组,每行元素数量为奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60114338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com