首页 > 解决方案 > 如何在使用动态二维数组时修复此代码

问题描述

我正在使用动态二维数组,需要特定索引的值,但它没有打印正确的值。

```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++;
}```

我希望输出是每个子集的值,但实际输出完全不同。

标签: c++pointers

解决方案


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

推荐阅读