JProgrammer
JProgrammer

Reputation: 1

Sorting array of structures in C error

I am writing a phonebook application in C. I have an array (sort2) of structure Nodes (contacts). I am trying to sort the array by nodes->pnum (phone number); s is the number of nodes in array. For some reason, the loop creates an error after first iteration. Why?

for(i=0; i<s;i++)
{
    for(j=0;j<s;j++)
    {
       num1= sort2[i];
       num2= sort2[j];
       if(num1->pnum<num2->pnum)
       {
            temp=sort2[j];
            sort2[j]=sort2[j+1];
            sort2[j+1]=temp;
            printf("%s",sort2[j]->lname);
            printf("%s",sort2[j+1]->lname);
        }
    }
}

Upvotes: 0

Views: 94

Answers (2)

OshoParth
OshoParth

Reputation: 1552

In the above code when you refer to sort2[j+1] at the last iteration of the loop it would result into access to the garbage memory as array indexing starts from 0 so the last index is limit-1 i.e s-1 in this case but code will access sort[s]. Thus this would result into abnormal termination of the program in certain cases.

And starting the inner loop from the next value of outer loop counter would save some iterations of your code.

so try

for(i=0; i<s;i++)
{
   for(j=(i+1);j<(s-1);j++)
   {
     num1= sort2[i];
     num2= sort2[j];
     if(num1->pnum<num2->pnum)
     {
        temp=sort2[j];
        sort2[j]=sort2[j+1];
        sort2[j+1]=temp;
        printf("%s",sort2[j]->lname);
        printf("%s",sort2[j+1]->lname);
     }
   }
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206637

You are accessing beyond the bounds of the array in the following lines when j is equal to s-1:

        sort2[j]=sort2[j+1];
        sort2[j+1]=temp;
        printf("%s",sort2[j+1]->lname);

I think you meant to use:

        sort2[j]=sort2[i];
        sort2[i]=temp;
        printf("%s",sort2[i]->lname);

Upvotes: 1

Related Questions