If you want to treat each row as an individual object, a 2D array is easier to work with and visualize. A good way to swap rows is a second array of pointers that point into the matrix. You swap those pointers for different sorting options and the matrix doesn't ever change:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define XSZ 3
#define YSZ 12
void PrintMatrix(int **pmat, int xsz, int ysz);
void ReverseMatrix(int **pmat, int sz);
int main()
{
int matrix[][YSZ] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35
};
int *pmat[XSZ];
int x;
for (x = 0; x < XSZ; ++x) pmat[x] = matrix[x];
PrintMatrix(pmat, XSZ, YSZ);
printf("\n");
ReverseMatrix(pmat, XSZ);
PrintMatrix(pmat, XSZ, YSZ);
return EXIT_SUCCESS;
}
void PrintMatrix(int **pmat, int xsz, int ysz)
{
int x, y;
for (x = 0; x < xsz; ++x)
{
for (y = 0; y < ysz; ++y)
{
printf("%-3d", pmat[x][y]);
}
printf("\n");
}
}
void ReverseMatrix(int **pmat, int sz)
{
int x, y;
for (x = 0, y = sz - 1; x < y; ++x, --y)
{
int *temp = pmat[x];
pmat[x] = pmat[y];
pmat[y] = temp;
}
}
It also works with a 1D array like the one in your code. As long as you work with pmat instead of matrix, the only difference is how pmat is constructed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define XSZ 3
#define YSZ 12
void PrintMatrix(int **pmat, int xsz, int ysz);
void ReverseMatrix(int **pmat, int sz);
int main()
{
int matrix[] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35
};
int *pmat[XSZ];
int x, k = 0;
for (x = 0; x < XSZ * YSZ; ++x)
{
if (x % YSZ == 0) pmat[k++] = &matrix[x];
}
PrintMatrix(pmat, XSZ, YSZ);
printf("\n");
ReverseMatrix(pmat, XSZ);
PrintMatrix(pmat, XSZ, YSZ);
return EXIT_SUCCESS;
}
void PrintMatrix(int **pmat, int xsz, int ysz)
{
int x, y;
for (x = 0; x < xsz; ++x)
{
for (y = 0; y < ysz; ++y)
{
printf("%-3d", pmat[x][y]);
}
printf("\n");
}
}
void ReverseMatrix(int **pmat, int sz)
{
int x, y;
for (x = 0, y = sz - 1; x < y; ++x, --y)
{
int *temp = pmat[x];
pmat[x] = pmat[y];
pmat[y] = temp;
}
}