首页 > 解决方案 > Why my code is not printing the sorted array?

问题描述

Why the code isn't printing anything? what this code is supposed to do is sorting the 2d array in that way: the 2d array represents a {x,y}, then the code needs to sort it, the rows which contain x < 0 need to be first and the rows with x>=0 need to be next. the swap function here is to swap between two rows. now when I try printing the sorted array, I get nothing in the output

#include <stdio.h>
void swap(int p1[], int p2[]);
int arrange(int p[][2], int n);


void swap(int p1[], int p2[]){
  for(int i=0; i<2; i++){
    int temp=p1[i];
    p1[i]=p2[i];
    p2[i]=temp;
  }
}

int arrange(int p[][2], int n){
  int idx=0;
  for(int i=0; i<n; i++){
    if(p[i][0] >= 0 && (i+1)<n)
        if(p[i+1][0] <0) {
            swap(&p[i][0],&p[i+1][0]);
            idx++;
        }
    else if(p[i][0]<0)
        idx++;
  }
return 1;
}

int main()
{
  int a[4][2]={{1,2},{6,7},{-10,5},{0,1}};
  arrange(a[4][2], 4);
  for(int i=0; i<4; i++){
        printf("{%d, %d}, ", a[i][0], a[i][1] );
  }

}

标签: carraysfunctionpointersmultidimensional-array

解决方案


为什么代码不打印任何东西?

因为它不能编译,因为你的编译器应该给出错误和警告。

为了修复错误,请更改此:

arrange(a[4][2], 4);

对此:

arrange(a, 4);

附录:

这是带有Wall标志的 GCC 给我的警告:

prog.cc: In function 'int arrange(int (*)[2], int)':
prog.cc:17:7: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
17 |     if(p[i][0] >= 0 && (i+1)<n)
   |

为了解决该警告,我将您的代码更改为:

if(p[i][0] >= 0 && (i+1)<n) {
    if(p[i+1][0] <0) {
        swap(&p[i][0],&p[i+1][0]);
        idx++;
    }
} else if(p[i][0]<0) {
    idx++;
}

推荐阅读