Nasif Imtiaz Ohi
Nasif Imtiaz Ohi

Reputation: 1713

sorting of 2d arrays in C

i'm a beginner in c. and a little bit confused about 2-d arrays which was pretty easy in python. let's suppose i declare an array[100][2] and take their readings. then i want to sort the elements through one dimension only. if i couldn't make myself clear, here's the code which runs perfectly in python(this logic). but in c, it gives error while sorting.

int array[100][2],i,j,n=50,temp[1][2];
for(i=0;i<n;i++){
    scanf("%d %d",&list[i][0],&list[i][1]);
}
/*heres's the sorting part which gives error*/

for(i=0;i<n-1;i++){
    for(j=i+1;j<n;j++){
        if(list[j][1]>list[i][1]){
            temp=list[i];
            list[i]=list[j];
            list[j]=temp;
        }
    }
}

so what should be the correct approach in C? if you haven't understand my question, please comment!

Upvotes: 2

Views: 409

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Your code is clean except for the part that you use to exchange the two-element arrays. There are two ways to fix it:

  • Use an alternative representation of the array - int *array[100] in which case you'll need to malloc and free individual elements, or
  • Use memcpy to exchange two-element arrays in your swap code.
  • With only two elements to swap, you can exchange two-element arrays one integer at a time without using memcpy

This is one way of doing it:

int temp[2];
memcpy(temp, list[i], sizeof(temp));
memcpy(list[i], list[j], sizeof(temp));
memcpy(list[j], temp, sizeof(temp));

Upvotes: 3

Related Questions