矩阵使用指针C++没有动态分配

所以我有一个赋值可以使用指针读取矩阵并使用指针显示它我也想知道为什么它总是在错误的地方添加一行并且它不显示矩阵也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;
}

回答

你的错误在这里

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

那应该是

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

和这里同样的错误

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

那应该是

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

但是你为什么要使用ptr为什么不直接使用Mat呢?

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

您认为使用指向矩阵的指针有什么好处,为什么不直接使用矩阵本身?

请注意,您的代码不是使用指针的矩阵,而是指向矩阵的指针,这根本不是一回事。所以也许你误解了你被要求做的事情。


以上是矩阵使用指针C++没有动态分配的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>