0

I have created a program to build a two dimensional array by taking user input using dynamic memory allocation in c++. The program has been compiled successfully and is running too but only creating small 2d arrays (like having size 2x2). When I try to create a larger size array, the exe program get stop after taking user input showing a small window pops up displaying "array.exe has stop working". Please guide me in identifying the problem.

{  
    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;
}
Eduardo Pascual Aseff
  • 1,118
  • 2
  • 9
  • 22

1 Answers1

1

Your problem is here:

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)
}

Check this reformatted code snippet for more clean code as well:

#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;
}
faressalem
  • 524
  • 4
  • 19