1. ## How do I print this matrix defined with pointers? PLEASE HELPPP

I defined this matrix with pointers, but I couldn't figure out how to print like a normal matrix print. like :

Code:
```for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
cout << M[i][j] << "\t";

cout << "\n";
}```

/////////////////////MY CODE/////////////////////////////

Code:
```#include<iostream>
#include<math.h>
#include<time.h>
using namespace std;
#define SIZE 20

void print_matrix2(int M[][SIZE], int a);

int main() {
int M[SIZE][SIZE] = {};
int N[SIZE][SIZE] = {};
int P[SIZE][SIZE] = {};
int* ptrMatris = &M[0][0];
int* ptrMatris2 = &N[0][0];
int* ptrMatris3 = &P[0][0];
int size, a,i;
srand(time(NULL));

cout << "enter size: " << endl;
cin >> size;

a = sqrt(size);

for (i = 0;i < size;i++)
{
*(ptrMatris+i) = rand() % 11;
*(ptrMatris2 + i) = rand() % 11;
}

/*cout << "----MATRIX - 1----" << endl;
print_matrix2(M, a);
cout << endl;
cout << "----MATRIX - 2----" << endl;
print_matrix2(N, a);
cout << endl;
*/

system("pause");
}

void print_matrix2(int M[][20],int a)
{
int i, j;
for (i = 0; i < a; i++)
{
for (j = 0; j < a; j++)
cout << M[i][j] << "\t";

cout << "\n";
}
}```

2. I've been trying to solve this problem for 2 days but I couldn't find it. Please help!!!!!!

3. You've "flattened" your matrix into a vector, so if you want to print the vector as a matrix again, you need to compute the index of each entry in the matrix. It seems like a waste of effort when you can directly use the 2D array as the matrix.

4. yes I think you are right. So how do I get the product of two matrices in this way with the help of pointers?
Originally Posted by laserlight
You've "flattened" your matrix into a vector, so if you want to print the vector as a matrix again, you need to compute the index of each entry in the matrix. It seems like a waste of effort when you can directly use the 2D array as the matrix.

5. > int M[SIZE][SIZE]
You have a block of memory that looks like this, if you were to subscript it.
In actuality, it's all just one contiguous block of SIZE*SIZE*sizeof(int) bytes.

This is what it looks like for SIZE=10
Code:
```..........
..........
..........
..........
..........
..........
..........
..........
..........
..........```
> cin >> size;
> a = sqrt(size);
OK, say you input 9 for size, so a will be 3.
Then run your loops.

If you flatten the matrix, this is what you get in memory.
Code:
```RRRRRRRRR.
..........
..........
..........
..........
..........
..........
..........
..........
..........```
If you didn't flatten it, you would have this instead.
Code:
```RRR.......
RRR.......
RRR.......
..........
..........
..........
..........
..........
..........
..........```
Now this is something you could just pass to
void print_matrix2(int M[][20],int a)
without any further effort.

So why can't you do this in main?
Code:
```for (i = 0; i < a; i++)
for (j = 0; j < a; j++)
M[i][j] = rand() % 11;```

Popular pages Recent additions