0

我的类变量之一是二维数组。大小取决于用户输入。用户可以输入可能超过他的硬件限制的大小。所以我想妥善处理这个问题。下面的代码是否正确?

        int counter;
        try
        {
            int size = 20000;//this is actually from user input
            array = new double*[size];
            for(counter = 0; counter < size; counter++)
                array[counter] = new double[size];
        }
        catch(std::bad_alloc)
        {
            try
            {
                for(int i = 0; i < counter; i++)
                    delete[] array([i]);

                delete[] array;
                array = NULL;

                //display limitation message
                size = 2;
                array = new double*[size];
                for(int i = 0; i < size; i++)
                    array[i] = new double[size];
            }
            //catch again & exit application
        }
4

1 回答 1

1

你最好的选择是:

std::vector<std::vector<double>>  array(size, std::vector<double>(size));

但是,如果您必须手动执行此操作,则:

void init_array(int size)
{
    int counter;
    try
    {
        array = new double*[size];

        // Don't shadow counter here.
        for(counter = 0; counter < size; counter++)
        {
            array[counter] = new double[size];
        }
    }
    catch(std::bad_alloc)
    {
        // delete in reverse order to mimic other containers.
        for(--counter; counter >= 0;--counter)
        {
            delete[] array[counter];
        }

        delete[] array;

        // retry the call with a smaller size.
        // A loop would also work. Depending on context.
        // Don't nest another try{} catch block. because your code will
        // just get convoluted.
        init_array(size/2);
    }
于 2013-10-21T03:51:44.897 回答