簡體   English   中英

在C錯誤中對結構數組進行排序

[英]Sorting array of structures in C error

我正在用C編寫電話簿應用程序。我有一個結構為Nodes(聯系人)的數組( sort2 )。 我試圖按nodes->pnum (電話號碼)排序數組; s是數組中節點的數量。 由於某種原因,循環在第一次迭代后會產生錯誤。 為什么?

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

j等於s-1時,您將在以下幾行中訪問數組的邊界:

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

我認為您打算使用:

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

在上面的代碼中,當您在循環的最后一次迭代中引用sort2[j+1]時,由於數組索引從0開始,因此將導致對垃圾內存的訪問,因此最后一個索引為limit-1,即s-1大小寫,但代碼將訪問sort[s] 因此,在某些情況下,這將導致程序異常終止。

從外部循環計數器的下一個值開始內部循環將節省代碼的某些迭代。

所以嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM