Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

sorting - Sort a matrix row wise (c programming)

I wrote this code for sorting an nxn matrix: odd rows in descending order, double rows in ascending order, but it doesn't pass the compiler stage.

What did I do wrong?

It mostly tells me this: assignment to 'int' from 'int *' makes integer from pointer without a cast (how can I solve this problem)?

#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("
");
  }

  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should change your matrix allocation to this:

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

(1): Declaring an array of pointers of size n x int*.

(2): Where each pointer in this array points to an array of integers of size n x int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...