簡體   English   中英

C 編程:Function 使用指針對數組進行排序

[英]C programming: Function using pointers to sort array

我對這個 function 有一些問題。 其主要目的是按節數按降序對類數組(如下)進行排序。 這是類的數組:

CIS_CLASSES *pCls, *pLast;
CIS_CLASSES  clsList[NUM_CLS] =
{
    {"CIS 35A", 2, {61, 63}},
    {"CIS 35B", 1, {62}},
    {"CIS 41A", 3, {1, 2, 61}},
    {"CIS 28",  1, {61}},
    {"CIS 22C", 4, {3, 4, 61, 63}},
    {"CIS 26B", 1, {61}},
    {"CIS 22B", 8, {1, 2, 3, 4, 6, 61, 62, 63}},
    {"CIS 29",  1, {61}},
    {"CIS 22A", 8, {1, 3, 5, 6, 7, 8, 61, 63}},
};

我還使用 struct 定義了 NUM_CLS:

#define NUM_CLS 9

typedef struct
{
    char  course[10];
    int   noSections;
    int   sections[16];
    int final;
} CIS_CLASSES;`

這是 function:

void sortDescend(CIS_CLASSES  list[], CIS_CLASSES *pLast);
{
    CIS_CLASSES *pCurr;
    CIS_CLASSES *pWalk;

    for (pCurr = list- 1; pCurr < pLast; pCurr++)
    {
        CIS_CLASSES temp = *pCurr;
        pWalk = pCurr - 1;
        while (pWalk >= 0 && temp.final > pLast->list[pWalk].final)
        {
            pLast->list[pWalk + 1] = pLast->list[pWalk];
            pWalk--;
        }
        pLast->list[pWalk + 1] = temp;
    }
  }
}

當我嘗試運行此代碼時,我收到錯誤消息:“CIS_CLASSES”中沒有名為“list”的成員。 但我不明白為什么? 我怎樣才能讓它運行? 如果我遺漏了什么,請告訴我!

查看您的結構,我在那里看不到元素list

typedef struct
{
    char  course[10];
    int   noSections;
    int   sections[16];
    int final;
} CIS_CLASSES;

所以

pLast->list[pWalk].final

必須失敗。

謝謝大家:我將我的代碼更新為:

    void sortDescend(CIS_CLASSES  list[], CIS_CLASSES *pLast);

{

CIS_CLASSES *pCurr;
 CIS_CLASSES *pWalk;

for (pCurr = list+1; pCurr < pLast; pCurr++)
{
    CIS_CLASSES temp = *pCurr;
    pWalk = pCurr - 1;
    while (pWalk >= 0 && strcmp(temp.course, pWalk->course) > 0)
   {
         *(pWalk + 1) = *pWalk;
          pWalk--;
   }
   *(pWalk + 1)  = temp;
}

} }

請嘗試執行以下操作。

void sortDescend(CIS_CLASSES  pInput[], CIS_CLASSES **pOutput);
{
    // pOutput should be declared in your main function as the following
    // CIS_CLASSES **pOutput = (CIS_CLASSES **)malloc(NUM_CLS * sizeof(PVOID));

    // copy pointer arrays of CIS_CLASSES list elements
    for(int i=0; i<NUM_CLS; i++)
    {
        pOutput[i] = &pInput[i];
    }

    // bubble sort
    for (int i=0; i<NUM_CLS-1, i++)
    {
        for (int j=i+1; j<NUM_CLS; j++)
        {
            CIS_CLASSES temp = *pCurr;
            if(pOutput[i]->noSection < pOutput[j]->noSection)
            {
                pCurr = pOutput[i];
                pOutput[i] = pOutput[j];
                pOutput[j] = pCurr;
            }
        }
    }
    // You can access the descending sorted list item like pOutput[index]->course, ... 
}

暫無
暫無

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

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