c++ - 如何在使用动态二维数组时修复此代码
问题描述
我正在使用动态二维数组,需要特定索引的值,但它没有打印正确的值。
```int u=5;//No. of elements
int S[u];
int i=0;
while(i<u)//elements in universal set
{
cin>>S[i];
i++;
}
int n;
cin>>n;//no. of subset
i=0;
int subcost[n];
int **subset;
subset=new int*[n];
while(i<n)
{
int l,c;
cin>>l;//size of ith subset
subset[i]=new int[l];
int j=0;
while(j<l)//Elements in each subset
{
cin>>subset[i][j];
j++;
}
cin>>c;//cost for each subset
subcost[i]=c;
i++;
}
i=0;
while(i<n)
{
int j=0;
int s=*subset[i];
while(j<s)
{
cout<<subset[i][j]<<"\n";
j++;
}
i++;
}```
我希望输出是每个子集的值,但实际输出完全不同。
解决方案
arr[i]=new int[n1];
对做什么有误解new
。(也许您来自 Java?)这不存储值为 的整数n1
。相反,它会创建一个大小为n1
.
对于数组来说,只有一个指针级别就足够了:
int n = 5;
int i = 0;
int *arr;
arr = new int[n];
arr[i] = 100;
cout << arr[i] << endl; // output: 100
delete[] arr; // remember to deallocate – otherwise memory leaks will haunt your system!
如果您正在寻找 2D 数组,指向指针 ( **
) 的指针将起作用。
int **arr;
arr = new int[n]; //
arr[0] = new int[n]; // allocate first array
arr[0][0] = 100; // set first element of first array
delete[] arr[0];
delete[] arr; // deallocate
推荐阅读
- c++ - 在树莓派上找不到 QtSerialPort/QSerialPort 和 QSerialPort
- excel - GNUplot:有没有一种方法可以用 gnuplot 从 excel 电子表格中绘制数据?
- python - Django:自动保存外键字段
- python - 在不同维度的两个数据框之间插入和匹配缺失值
- oracle - 长度为 39 位的 Oracle 数字列的 Hive 数据类型
- amazon-s3 - 为什么 s3 不能与 proxy_set_header 主机 $http_host 一起使用;在 Nginx 中?
- javascript - 期中考试要求我从 XML 文档中生成“国家”的计数和“联系人标题”的计数
- android - Android 项目在物理设备上运行良好,但在由 google playstore prelease/robotest 运行时失败
- python - 选择具有最小连续计数的随机索引子集
- flutter - SystemChrome SystemUIMode 有没有办法始终显示顶部状态栏但具有沉浸式粘性底部?