【问题标题】:2D array using dynamic memory allocation error二维数组使用动态内存分配错误
【发布时间】:2020-08-08 14:36:11
【问题描述】:

我创建了一个程序,通过使用 c++ 中的动态内存分配获取用户输入来构建二维数组。该程序已成功编译并正在运行,但仅创建小型二维数组(如大小为 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;
}

【问题讨论】:

  • “ptr[i] = new int[i];”应该是“ptr[i] = new int[a];”并且封闭循环应该从 0 到 b。

标签: c++ multidimensional-array dynamic-memory-allocation


【解决方案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)
}

检查这个重新格式化的代码 sn-p 以获得更干净的代码:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2014-07-19
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多