按行对矩阵进行排序(c 编程)

时间:2021-01-06 12:30:32

标签: c sorting matrix

我编写了这段代码来对 nxn 矩阵进行排序:奇数行按降序排列,双行按升序排列,但它没有通过编译器阶段。

我做错了什么?

它主要告诉我这一点:从 'int *' 赋值给 'int' 会从指针生成整数而不进行强制转换(我该如何解决这个问题)?

#include <stdio.h>
#include <stdlib.h>
   
int comp_a(int a, int b) {
  if (a < b) {
    return 1;
  } else {
    return 0;
  }
}
    
int comp_d(int a, int b) {
  if (a > b) {
    return 1;
  } else {
    return 0;
  }
}

void sort(int a[], int n, int (*comp)(int, int)) {
  int t;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n - 1; j++) {
      if (comp(a[j], a[j + 1]) == 0) {
        t = a[j];
        a[j] = a[j + 1];
        a[j + 1] = t;
      }
    }
  }
}
    
int main() {
  int n;
  printf("Enter the dimension of matrix(n): ");   
  scanf("%d", &n);                                
 
  int *mat = (int*)calloc(n, sizeof(int));

  for (int i = 0; i < n; i++) {
    mat[i] = (int*)calloc(n, sizeof(int));
  }
    
  for (int i = 0; i < n; i++) {
    printf("Enter row [%d]: ", i);
    for (int j = 0; j < n; j++) {
      scanf("%d", &mat[i][j]);
    }
  }
    
  for (int i = 0; i < n; i++) {
    if (i%2 == 0) {
      sort(mat[i], n, &comp_a);
    } else {
      sort(mat[i], n, &comp_d);
    }
  }
    
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      printf("%d ", mat[i][j]);
    }
    printf("\n");
  }

  return 0;
}

2 个答案:

答案 0 :(得分:3)

您应该将矩阵分配更改为:

int **mat = (int**)calloc(n, sizeof(int*)); // (1)
for(int i = 0; i < n; i++) {
    mat[i] = (int*)calloc(n, sizeof(int));  // (2)
}

(1): 声明一个大小为 n x int* 的指针数组。

(2):该数组中的每个指针都指向一个大小为 n x int 的整数数组。

答案 1 :(得分:0)

我改变了你的矩阵分配

int *mat = (int*)calloc(n, sizeof(int));
for(int i = 0; i < n; i++) {
    mat[i] = (int*)calloc(n, sizeof(int));
}

int mat[n][n];

我改变了for循环

for(int i = 0; i < n; i++) {
    for(int j = 0; j < n - 1; j++) {
        if(comp(a[j], a[j + 1]) == 0)

因为他花了很多时间(跑步的时间)

 for(int i = 0; i < n; i++) {
    for(int j = i+1; j < n; j++) {
        if(comp(a[i], a[j]) == 0) 

我的代码:

#include <stdio.h>
#include <stdlib.h>


int comp_a(int a, int b) {
if(a < b) {
    return 1;
}
else {
    return 0;
}
}

int comp_d(int a, int b) {
if(a > b) {
    return 1;
}
else {
    return 0;
}
}

void sort(int a[], int n, int (*comp)(int, int)) {
int t;
for(int i = 0; i < n; i++) {
    for(int j = i+1; j < n; j++) {
        if(comp(a[i], a[j]) == 0) {
            t = a[j];
            a[j] = a[i];
            a[i] = t;
        }
    }
}
}

int main() {
int n;
do
{
    printf("Enter the dimension of matrix(n): ");
    scanf("%d", &n);
}while(n<1);
int mat[n][n];
for(int i = 0; i < n; i++) {
    printf("Enter row [%d]: ", i);
    for(int j = 0; j < n; j++) {
        scanf("%d", &mat[i][j]);
    }
}

for(int i = 0; i < n; i++) {
    if(i%2 == 0) {
        sort(mat[i], n, &comp_a);
    }
    else {
        sort(mat[i], n, &comp_d);
    }
}

for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
        printf("%d ", mat[i][j]);
    }
    printf("\n");
}

return 0;
}