Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
        }
    }
}
share|improve this question
1  
This is what qsort is for. Anyway, you'd better hope sort2 has more than s elements. –  chris 21 hours ago
    
Even when bug-fixed, that is a brutally inefficient way of sorting. –  Jonathan Leffler 21 hours ago

2 Answers 2

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);
share|improve this answer
    
Thank you but I tried this it did not work.. –  JProgrammer 21 hours ago
    
@JProgrammer, what do you mean by that? Is sorting not working? Are you getting memory access related errors? –  R Sahu 21 hours ago
    
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 –  JProgrammer 21 hours ago

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);
     }
   }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.