Search code examples
c++pointersmultidimensional-arraycompiler-errorsdynamic-arrays

Error (std::bad_array_new_length) in a 2d array textbook example (Absolute C++, Savitch)


Here is a textbook example from Absolute C++ by Walter Savitch:

enter image description here

I tried a different version but got an error, so I tried typing out the code exactly:

#include <iostream>
using namespace std;
typedef int* IntArrayPtr;

int main()
{
    int d1, d2;
    cout << "Enter dimensions (row*col): \n";
    cin >> d1, d2;
    IntArrayPtr *m = new IntArrayPtr[d1]; //Get me a d1 sized array of pointers
    int i,j;
    for(i=0; i<d1; i++)
        m[i] = new int[d2]; //each element in the array should be an array of size d2
    //m is now a d1*d2 array

    cout << "Enter " << d1 << " rows of " << d2 << " integers:\n";
    for(i=0;i<d1;i++)
        for(j=0;j<d2;j++)
            cin >> m[i][j];
    
    cout << "Your arry:\n";
    for(i=0;i<d1;i++)
        {for(j=0;j<d2;j++)
            cout << m[i][j] << " ";
        cout << endl;
        }

    for (i = 0; i < d1; i++)
        delete m[i]; //delete each pointer
    delete[] m; //delete the master pointer

    return 0;
    

}

And when I tried running the example in the text, I got an error as soon as I entered the dimensions. enter image description here

Can anyone help me identify the problem? No other error has occurred with an example from this textbook so far.


Solution

  • Your error is likely on this line: cin >> d1, d2;

    It should be cin >> d1 >> d2;

    Compiling with a modicum of warning flags set, -Wall -Wextra in my case, would have revealed this to you immediately.

    Here is the warning I received:

    main.cpp:9:16: warning: expression result unused [-Wunused-value]
        cin >> d1, d2;
                   ^~
    1 warning generated.
    

    By utilizing the comma operator, yes that is a thing, you are throwing away one of your inputs and not creating an array of the size you think you are.