[使用动态内存分配错误的2D数组

问题描述 投票:0回答:1

我已经创建了一个程序来通过使用c ++中的动态内存分配获取用户输入来构建二维数组。该程序已成功编译并正在运行,但仅创建了较小的2d数组(例如大小为2x2)。当我尝试创建较大尺寸的数组时,exe程序会在用户输入弹出后弹出一个小窗口并显示“ array.exe停止工作”后停止。请指导我确定问题所在。

{  
    int a,b,i,j;
    cout << "how many columns do you want in array ? ";
    cin >> a;
    cout << "how many rows do you want in array ";
    cin >> b;
    int * * ptr = new int * [b];
    for(i=0;i<a;i++){
        ptr[i] = new int[i];
    }
    for(i=0;i<b;i++){
        cout << "enter elements of row no. " <<  i+1 << endl;
        for(j=0;j<a;j++){  
            cout << "enter element no. " <<  j+1 << endl;
            cin >> ptr[i][j];
        }
    }
    cout << "array completed.press enter to view the array" << endl;
    _getch();
    system("cls");
    for(i=0;i<b;i++){
        for(j=0;j<a;j++){
            cout << ptr[i][j] << "  ";
        }
        cout << "\n";
    }
    for(i=0;i<a;i++){
        delete[] ptr[i];
    }
    delete[] ptr;

    return 0;
}
c++ multidimensional-array dynamic-memory-allocation
1个回答
1
投票

您的问题在这里:

for(i=0;i<a;i++){       // iterate through rows (b) not columns (a)
 ptr[i] = new int[i];   // you should allocate memory with the size of columns (a) not (i)
}

也请检查此重新格式化的代码段以获取更干净的代码:

#include <iostream>

// a x b matrix
#define a 4
#define b 5

int main()
{
    int **ptr = new int *[b]; // create array of pointers of size (b)

    for (int i = 0; i < b; ++i)
        ptr[i] = new int[a];    // allocate memory of size (a) for each column

    int elements_count = 0;     // 0-indexed cell counter
    for (int i = 0; i < b; ++i)
    {
        for (int j = 0; j < a; ++j) 
        {
            ptr[i][j] = elements_count; // assign cell number to allocated memory
            elements_count++;
        }
    }

    for (int i = 0; i < b; ++i)
    {
        for (int j = 0; j < a; ++j)
            std::cout << ptr[i][j] << " ";

        std::cout << std::endl;
    }

    for (int i = 0; i < a; ++i)
        delete[] ptr[i];

    delete[] ptr;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.