的二维阵列C动分配++ [英] Dynamic Allocation of two-dimensional array C++

查看:134
本文介绍了的二维阵列C动分配++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty新的C ++和我需要dynamicacally分配二维数组。没有错误,但在运行时,我设置了秩序和第一排,然后我得到一个运行时错误:段错误......这里是code:

 的#include<&iostream的GT;使用命名空间std;双** allocateDynamicArray(INT与秩序){
    双** ARR =新的双* [为了]
    的for(int i = 0; I<顺序;我++){
            * ARR =新的双[整理+ 1];
    }
    返回ARR;
}
无效deallocateDynamicArray(双**​​改编,诠释序){
    的for(int i = 0; I<顺序;我++){
        删除[]常用3 [I]
    }
    删除[] ARR;
}无效addAndPrintArray(双**​​改编,诠释序){
    COUT<< Zadejte prvky极拉杜<<为了<< ENDL;
    的for(int i = 0; I<顺序;我++){
        对于(INT J = 0; J<为了+ 1; J ++){
            COUT<< 极点[<< I<< ] [<< J<< ]:
            CIN>>改编[I] [J]。
        }
    }    的for(int i = 0; I<顺序;我++){
        对于(INT J = 0; J<为了+ 1; J ++){
            COUT<<改编[I] [J]<< ;
            如果(ARR [I] [J]小于10安培&;&安培;常用3 [I] [J]> -10){
                COUT<< ;
            }
            COUT<< ENDL;
        }
    }
}
诠释的main()
{
    INT秩序;
    CIN>>订购;
    双**的DynArray = allocateDynamicArray(订单);
    addAndPrintArray(的DynArray,顺序);
    deallocateDynamicArray(的DynArray,顺序);
    返回0;
}


解决方案

您忘了增加改编在初始化循环:

 的for(int i = 0; I<顺序;我++){
     * ARR =新的双[整理+ 1];

做到这一点,而不是:

 的for(int i = 0; I<顺序;我++){
     改编[I] =新的双[整理+ 1];

同样,除非你要改变的行中的一个的尺寸,上面的方法相比,分配2维阵列的这种方式是低效的:

 双** allocateDynamicArray(INT与秩序){
    双** ARR =新的双* [为了]
    INT COLS =订单+ 1;
    双池* =新的双[为了* COLS]。
    的for(int i = 0; I<秩序;我++,池+ = COLS){
           改编[I] =池;
    }
    返回ARR;
}无效deallocateDynamicArray(双**​​ ARR){
        删除[] ARR [0];
        删除[] ARR;
    }

只是两次调用新[] ,只有两次调用删除[] 需要,无论是行和列的数目。

另外一个原因,为什么第二种形式上面应在第一种形式的青睐是在新[] 可能会引发异常的情况。

使用第一种形式,如果这个循环某处,新[] 抛出一个异常,你必须把所有的previous成功分配的轨道,并通过发出删除[] 通话回滚他们。不是很好。

使用第二种形式中,如果第一次调用新[] 失败,不存在损害作为异常无泄漏会被抛出(因为没有记忆被成功分配)。如果第二次调用新[] 失败,所有你需要做的是提供(a 抓内部块)删除第一次调用到新[]

 双** allocateDynamicArray(INT与秩序){
    双** ARR =新的双* [为了]
    INT COLS =订单+ 1;
    尝试{
       双池* =新的双[为了* COLS]。
    }
    赶上(则为std :: bad_alloc急症)
    {
       删除[] ARR; //删除previous分配
       返回NULL; //或再次引发此异常
    }
    的for(int i = 0; I<秩序;我++,池+ = COLS)
        改编[I] =池;
    返回ARR;
}

注意的std ::矢量做所有这些工作给你。但是,如果由于某种原因,你不能使用向量,二维数组将保持其整个生命周期相同的大小,使用第二种形式。

在另外,第二方法减轻了堆的存储器碎片。取而代之的调用分配器,只有一个呼叫到分配作出分配数据。如果是,说1000或10,000,你马上看到它是更好地使2呼叫新[] 不是万呼叫新[]

Hi I'm pretty new to C++ and I need to dynamicacally allocate two-dimensional array. No error but in runtime when I set a order and first row then I get a runtime error: "Segmentation Fault"...Here's code:

#include <iostream>

using namespace std;

double ** allocateDynamicArray(int &order){
    double ** arr = new double *[order];
    for(int i = 0;i < order; i++){
            *arr = new double[order+1];
    }
    return arr;
}
void deallocateDynamicArray(double **arr, int order){
    for(int i=0; i<order; i++){
        delete [] arr[i];
    }
    delete [] arr;
}

void addAndPrintArray(double **arr, int order){
    cout << "Zadejte prvky pole radu " << order << endl;
    for(int i=0; i< order; i++){
        for(int j=0; j< order+1; j++){
            cout << "Pole[" << i << "][" << j << "]: ";
            cin >> arr[i][j];
        }
    }

    for(int i=0; i< order; i++){
        for(int j=0; j< order+1; j++){
            cout << arr[i][j] << " ";
            if(arr[i][j] < 10 && arr[i][j] > -10){
                cout << " ";
            }
            cout << endl;
        }
    }
}
int main()
{
    int order;
    cin >> order;
    double **dynArray = allocateDynamicArray(order);
    addAndPrintArray(dynArray, order);
    deallocateDynamicArray(dynArray, order);
    return 0;
}

解决方案

You forgot to increment arr in your initialization loop:

for(int i = 0;i < order; i++){
     *arr = new double[order+1];

Do this instead:

for(int i = 0;i < order; i++){
     arr[i] = new double[order+1];

Also, unless your going to change the dimensions of one of the rows, the method above is inefficient compared to this way of allocating a 2 dimensional array:

double ** allocateDynamicArray(int &order){
    double ** arr = new double *[order];
    int cols = order+1;
    double *pool = new double [order * cols];
    for(int i = 0;i < order; i++, pool += cols){
           arr[i] = pool;
    }
    return arr;
}

void deallocateDynamicArray(double **arr){
        delete [] arr[0];
        delete [] arr;
    }

Just two calls to new[] and only two calls to delete[] are needed, regardless of the number of rows and columns.

The other reason why the second form above should be favored over the first form is in the case where new[] may throw an exception.

Using the first form, if somewhere in that loop, new[] throws an exception, you have to keep track of all of the previous successful allocations, and "roll them back" by issuing delete[] calls. Not nice.

Using the second form, if the first call to new[] fails, then there is no harm as the exception will be thrown without leakage (since no memory was successfully allocated). If the second call to new[] fails, all you need to do is to provide (inside of a catch block) the deletion of the first call to new[].

double ** allocateDynamicArray(int &order) {
    double ** arr = new double *[order];
    int cols = order+1;
    try {   
       double *pool = new double [order * cols];
    }
    catch (std::bad_alloc& e)
    {
       delete [] arr;  // delete previous allocation
       return NULL;  // or rethrow the exception here
    }
    for(int i = 0;i < order; i++, pool += cols)
        arr[i] = pool;
    return arr;
}

Note that std::vector does all of this work for you. However if for some reason you can't use vector, and the two dimensional array will remain the same size throughout its lifetime, use the second form.

In addition, the second method lessens memory fragmentation of the heap. Instead of rows calls to the allocator, only one call is made to the allocator to allocate the data. If rows were, say 1,000 or 10,000, you see right away it is better to make 2 calls to new[] instead of 10,000 calls to new[].

这篇关于的二维阵列C动分配++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆