1. Matrix Sorting using Pointer

I tried to use pointer arithmetic to sort a 2D matrix. The Code I've written was:

Code:
```#include<stdio.h>
#include<stdlib.h>

main()
{
int a[3][4], i, j, k, l, temp;

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
scanf("%d", (a+i*4+j));
}
}

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<3; k++)
{
for(l=0; l<4; l++)
{
if(*(a+i*4+j)<*(a+k*4+l))
{
temp = *(a+i*4+j);
*(a+i*4+j) = *(a+k*4+l);
*(a+k*4+l) = temp;
}
}
}
}
}

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
printf("%d\t", *(a+i*4+j));
}
printf("\n");
}

return 0;
}```
The compiler creates three message:
Line 27: Warning: Assignment makes int to pointer without a cast.
line 28: Incompatible types when assigning to type to type 'int[4]' from type 'int *'
line 29: Incompatible types when assigning to type to type 'int[4]' from type 'int'

I'm new to the whole programming thing. And I can not figure out what is wrong with my program as far my knowledge goes this should not be a problem. Help please.
Thanks in advance. And explain in detail.

2. I suggest getting the sort to work without using "pointer arithmetic"; then you can modify the code if needed back to using "pointer arithmetic".

Tim S.

3. I have already done it without pointer arithmetic. here is it:
Code:
```#include<stdio.h>
#include<stdlib.h>

main()
{
int a[3][4], i, j, k, l, temp;

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
scanf("%d", &a[i][j]);
}
}

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<3; k++)
{
for(l=0; l<4; l++)
{
if(a[i][j]<a[k][l])
{
temp = a[i][j];
a[i][j] = a[k][l];
a[k][l] = temp;
}
}
}
}
}

for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}

return 0;
}```
this works just fine.
Now i want to do it using pointers.

4. If you're going to use pointers like that - calculating your own row/column offset, then the array should be defined one dimensional such as a[12].

5. As the array is stored in a continuous memory block you can say that. Actually for a 1D array, I have sorted it using the pointer arithmetic.
However for a a[3][4] matrix to access the a[2][3] element the pointer notation is *(a+2*4+3); I wanted to use this to do the work. But not working.
But i need this block to work:
temp = *(a+i*4+j);
*(a+i*4+j) = *(a+k*4+l);
*(a+k*4+l) = temp;

i wonder what is wrong with it.

6. But you're not really using pointer arithmetic properly here.

Your approach is akin to array flattening, but that only works if your initial pointer is a pointer to the first element. The array name (for a 2D array) is not a pointer to the first element, but a pointer to the first row. When you do the addition, the effective sizeof for each array element pushes you way past the end of the array.

Besides, you should NOT have all those literal sizes in there.

This is your equivalent, for the print statement.
printf("%d\t", *(*(a+i)+j) );

7. Yes, you need to work on the sorting algorithm part.

8. Thanks Salem.