Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

matrix using pointers c++ without dynamic allocation

So i have an assigment that would read a matrix using pointers and show it using pointers also i wanna know why it always add a row where is exactly the mistake and it doesnt show the matrix also thnks

#include <iostream>

using namespace std;

int main ()
{
    int Mat[50][50],N,M;
    int (*ptr)[50][50];
    cout<<"number of lignes : ";
    cin>>N;
    cout<<"number of rows : : ";
    cin>>M;
    ptr=&Mat;
    
    for (int i=0;i<N;i++)
     {
        for (int j=0 ; j<M ;j++)
         {
              cout<<"fill the matrix [" <<i<<","<<j<< "] : " ;
              cin>>*ptr[i][j];  
         }
     }
    
    for (int i=0 ; i<N ; i++ )
     {
        for (int j=0 ; j<M ; j++)
        {
            cout<<*ptr[i][j] <<" ";
        }
        cout<"/n";
     }
    return 0;
}
question from:https://stackoverflow.com/questions/65541016/matrix-using-pointers-c-without-dynamic-allocation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your mistake is here

cin>>*ptr[i][j];

that should be

cin>>(*ptr)[i][j];

and the same error here

cout<<*ptr[i][j];

that should be

cout<<(*ptr)[i][j];

But why are you using ptr why not just use Mat instead?

cin>>Mat[i][j];
cout<<Mat[i][j];

What do you think is the benefit of using a pointer to your matrix, why not just use the matrix itself?

Note that your code isn't a matrix using pointers, its a pointer to a matrix, which is not the same thing at all. So maybe you've misunderstood what you have been asked to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...