*编辑:尽管如此,当第一行输入3列,第二行输入2列时,在输出中,第一行变成2元素作为第一行。

输出动态分配数量的设备并分别动态分配列数(每个设备的捕获数量)时出现问题...即,如果我尝试分配2个设备,然后为第一个设备分配两个“渔获”鱼(两列),第二个装备了三个渔获物,一切都很好...但是,如果我尝试为第二行(装备)尝试输入较少数量的列(“捕捉”),则在输出中第一行是“切断”的,例如,如果第一行有3列输入,第二行有2列输入,则在输出中,每行中只有两列(数字的索引)两行。

#include<iostream>

int main()
{
    using namespace std;

    int *sum;

    int *a = new int;
    int *b = new int;


    cout << "Total number of equips: ";
    cin >> *a;


    // Allocate a two-dimensional 3x2 array of ints
    int** ippArray = new int*[*a];
    for (int i = 0; i < *a+1; ++i) {
            ippArray[i] = new int[*b];
    }

    // fill the array

    for (int i = 1; i < *a+1; ++i) {
            cout << "Total number of catches for " << i << "th equip : ";
            cin >> *b;
            cout << "Equip number: " << i << endl;

            for (int j = 1; j < *b+1; ++j) {
                    cout << "Catch number: " << j << endl;
                    cin >> ippArray[i][j];
                    ippArray[i][j];
            }
    }

    // Output the array
    for (int i = 1; i < *a+1; ++i) {
        for (int j = 1; j < *b+1; ++j) {
                            cout << ippArray[i][j] << "  ";
                            *sum = *sum + ippArray[i][j];
                    }
                    cout << endl;
            }
            cout << endl;

            cout << "All catches of the all equipes: " << *sum-3;




            // Deallocate
            for (int i = 1; i < *a+1; ++i) {
                    delete [] ippArray[i];
            }
            delete [] ippArray;
            // Keep the window open
            cin.get();
            return 0;
        }

最佳答案

首先,除非确实需要,否则不要将整数变成指针(int *a = new int;)。这使代码更难阅读,如果有人必须维护您的代码,他们会称呼您为“漏洞”。

其次,int** ippArray = new int*[*a];结合多个用于执行此操作的点... for (int i = 1; i < *a+1; ++i)不好。 ippArray具有从0到*a的有效引用,因此应为for (int i = 0; i < *a; ++i)

编辑:尝试这样的http://ideone.com/4egQl3

Edit2:也是标准建议...

{
    std::vector<string> advice;
    advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!

10-07 19:11
查看更多