c - 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] );
}
}
解决方案
为什么代码不打印任何东西?
因为它不能编译,因为你的编译器应该给出错误和警告。
为了修复错误,请更改此:
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++;
}
推荐阅读
- angular - Ionic 4 Slider autoplay
- javascript - 什么是多文件上传示例的 js 验证:name="files[]"
- swift - 使用 ESTabBarController 添加标签栏
- python - for el in x ->TypeError: 'float' object is not iterable
- .net - Many system libraries in build folder when referencing .netstandard project
- wix - 当安装程序在卸载过程中运行时,如何防止 WIX 条件检测?
- php - 运行ajax后我无法从php获得响应
- javascript - 将 keyDown 按键更改为小写
- php - 如何在 Laravel 中加入相似的值和总和(相关表)?
- php - 如何修复迁移 Laravel 错误“PDOException 和 PDO::__construct”