首页 > 解决方案 > 为什么指针在对二维数组进行排序时不能正常工作?

问题描述

我使用此代码,但运行错误。它对某些数据进行了正确排序,但其余数据未正确排序。我想知道这段代码的错误在哪里,为什么?

#include<iostream>
using namespace std;
const int row=4;
const int col=4;
int main()
{

  int mat[][col]={{1,2,3,4},{2,8,4,1},{3,5,7,8},{7,6,6,5}};
  int arr[row][col];
  cout<<" first "<<endl;
  for(int i=0;i<row;i++){
     for(int j=0;j<col;j++){
         cout<<mat[i][j]<<" ";
     }
      cout<<endl;
   }

  for(int i=0;i < row;i++){
     for(int j=i+1;j <= col;j++){
        if(*(*(mat + 0) + i) >= *(*(mat + 0) + j)){
             temp= *(*(mat + 0) + i);
             *(*(mat + 0) + i) = *(*(mat + 0) + j);
             *(*(mat + 0) + j) = temp;
         }
     }
  }

  cout<<" after arrangement "<<endl;
  for(int i=0;i<row;i++){
     for(int j=0;j<col;j++){
        cout<<mat[i][j]<<" ";
     }
     cout<<endl;
  }
  return 0;
}

标签: c++

解决方案


目前尚不清楚您想要的排序规则是什么,但是,假设需要任何合理一致的排序,也许您会接受将数组转换为一维数组或指针并使用标准排序(如 qsort 或 std)以这种方式排序::sort ... 是否会导致未定义的行为或数组打包规则是否确保它始终被明确定义 - 如果您相信后者,那么这可能是您的答案。


推荐阅读