I'm not entirely sure what you mean by "connect the matrix with it".
You could add an extra column and put the sum there.
Code:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 4
#define COLS 4 // one extra to hold the sum
// Compare function for qsort, sorting rows by last column.
int cmp(const void *a, const void *b) {
return ((int*)a)[COLS-1] - ((int*)b)[COLS-1];
}
int main() {
int m[ROWS][COLS] = {
{ 5, 2, 3, 0 }, // init sum column to 0
{ 6, 5, 8, 0 },
{ 9, 2, 7, 0 },
{ 8, 9, 8, 0 }
};
// Calculate sums.
for (int r = 0; r < ROWS; ++r)
for (int c = 0; c < COLS - 1; ++c)
m[r][COLS-1] += m[r][c];
// Sort.
qsort(m, ROWS, sizeof m[0], cmp);
// Print.
for (int r = 0; r < ROWS; ++r) {
for (int c = 0; c < COLS; ++c)
printf("%2d ", m[r][c]);
putchar('\n');
}
return 0;
}