0

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);
        }
    }
}
2
  • 1
    This is what qsort is for. Anyway, you'd better hope sort2 has more than s elements. Commented Jul 31, 2014 at 14:51
  • Even when bug-fixed, that is a brutally inefficient way of sorting. Commented Jul 31, 2014 at 15:01

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@JProgrammer, what do you mean by that? Is sorting not working? Are you getting memory access related errors?
I get a run time error the loop goes through one time and seems to break at the second assignment of num1 and num2 which i know are being assigned the node structure there of type nodeptr as the array is that type
for(i=0; i<s;i++) { for(j=0;j<s;j++) is bad.
0

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);
     }
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.