class Matrix
{
public:
		int M;
			int N;
			double *ptr;
			
			Matrix(int m,int n)//constructor takes two ints
			{
				M = m;
				N = n;
				ptr = new double[M][N];
				assign(M,N);//call function
			}


			void assign(int M,int N)// method
			{
				for(int i = 0; i < M;i++)// i is a row
			{
				for (int j = 0; j < N; j++)// j is a column
				{
					ptr[M][N] = (double) 1000 + i * N + j;
					cout << ptr[M][N] << "\t"; //print values
					
				}//end for loop j
				cout << "\n";//print newline
			}//end for loop i

			}//end assign
};

Hello, the above code works fine when I use a 1d array to output the values. But when I attempt to do the same using a 2d array like above, it gives me errors. Anybody help?
Thanks.

You have:

ptr[M][N] = (double) 1000 + i * N + j;

M and N will always be outside of the array, and are the same every time through the loop.

You probably meant:

ptr[i][j] = (double) 1000 + i * N + j;

Same goes for the cout immediately after.

Silly mistake...thanks..but it still doesnt solve my problem.

the error I am getting is 'cannot convert from double(*)[1] to double?

Line 12 is this: ptr = new double[M][N]; . I don't think that you can do this. You probably want:

ptr = new double[M * N];

This will allocate you enough space, but means that you will also have to change lines 23 and 24, since you won't be able to use the [][] notation for accessing elements. You will have to use this instead:

for(int i = 0; i < M;i++)// i is a row
{
    for (int j = 0; j < N; j++)// j is a column
    {
        ptr[ i * N + j ] = (double) 1000 + i * N + j;
        cout << ptr[ i * N + j ] << "\t";
    }
    cout << "\n";
}

If you want to use the [][] notation, then you have to declare ptr as a pointer to a pointer to a double:

double **ptr;

And use a loop to new each row:

ptr = new double*[M];
for ( int i = 0; i < M; ++i )
   ptr[i] = new double[N];

Personally, I prefer the first way.

Hope that helps.

Thanks Ravenous....think I will stick with the first way as it is easier...although it is interesting to know how to do it the other way!! Thanks

This question has already been answered. Start a new discussion instead.