0

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.

SKYejin
  • 107
  • 5
  • `//m is now a d1*d2 array` Not quite. It's an array of `d1` pointers to `d1` arrays of `d2` `int`s. The distinction is important and can have significant impact on the performance of the program due to poor cache-friendliness.. – user4581301 Dec 24 '20 at 02:05
  • Looking at this, it's a wonder I was able to learn the language from Savitch in school. – sweenish Dec 24 '20 at 02:05
  • @sweenish do you recommend a different resource? – SKYejin Dec 24 '20 at 02:19
  • 1
    Savitch will get you there. But looking at that code, it won't be the smoothest ride. While there's no definitive best book, there's [the list of good books](https://stackoverflow.com/a/388282/6119582). – sweenish Dec 24 '20 at 03:41

1 Answers1

1

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.

sweenish
  • 4,793
  • 3
  • 12
  • 23