cin>>d1.u_star[grid][grid];
Grid is equal to 5 and you which means that your 2d array is 5x5.
by doing
d1.u_star[grid][grid]
you're trying to access the array's 6th element, which doesn't exist since you initialised it with a size of 5. (first element accessed with 0, second with 1, ..., 5th with 4)
You should define all those variable inside your main(), it's a bad idea to take the habit of having them as globals
Also by convention, const variables are in all caps.
You could also define display inside your struct Data.
Your main isn't returning any value.
You could do something like this (keep in mind I deleted one of the arrays, since you weren't using it anyway
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
using namespace std;
struct Data
{
Data(const int MAX) : max(MAX)
{
//dynamic allocation of 2d array (since max is a non-const var)
u_star = new double*[max];
for (int count = 0; count < max; count++) u_star[count] = new double[max];
};
int max;
double **u_star; //pointer to pointer to hold 2d array
void display() //display function
{
cout << "\n Your 2d array: \n";
for (int i = 0; i < max; i++)
{
for(int j = 0; j < max; j++)
{
cout << u_star[i][j] << "\t";
}
cout << "\n";
}
}
};
int main ()
{
const int MAX_GRID = 3; //max number of rows and columns
Data data(MAX_GRID);
for (int i = 0; i < MAX_GRID; i++)
{
cout << "\nRow " << i + 1 << ": \n";
for(int j = 0; j < MAX_GRID; j++)
{
cout << "Column " << j + 1 << ": ";
data.u_star[i][j] = 0;
cin >> data.u_star[i][j];
}
}
data.display();
return (0);
}
|
Row 1:
Column 1: 0.1
Column 2: 0.2
Column 3: 0.3
Row 2:
Column 1: 1.5
Column 2: 1.4
Column 3: 1.3
Row 3:
Column 1: 9.98
Column 2: 9.97
Column 3: 9.96
Your 2d array:
0.1 0.2 0.3
1.5 1.4 1.3
9.98 9.97 9.96
Exit code: 0 (normal program termination) |