簡體   English   中英

添加多個患者C指針

[英]Add more than one patient C Pointers

我的指針遇到了麻煩。 我正在嘗試將多名患者添加到我的列表中。 我知道怎么做,只是代碼給了我seg錯誤。

這是有問題的代碼:

void addPatient(int patientID) {
    Chartptr patients_chart;

    patients_chart = getChart(patientID);

    // if patient wasn't found, add new patient
    if (patients_chart == NULL) {
        Chartptr new_chart;

        // allocate and initialize new patient
        new_chart         = (Chartptr)malloc(sizeof(Chart));
        new_chart->id     = patientID;
        new_chart->buffer = NULL;

        // insert new patient into list
        new_chart->next   = patientList;
        patientList       = new_chart;

        // test print patient data
        printf("%d %d\n", new_chart->id, patientList->id);
    }
}

/*
*  getChart: given a patientID, return a pointer to their Chart
*/
Chartptr getChart(int patientID) {
    Chartptr foundChart = NULL;

    // find the patient chart with id
    foundChart = patientList;
    if (foundChart != NULL) { 
        while(foundChart->id != patientID) {
            foundChart = foundChart->next;
        }
    }

    return foundChart;
}

結構如下:

/*
*   Patient's health chart: ID + linked list of  health type readings
*/
typedef struct chartEntry* Chartptr;   /* pointer to a Chart */

typedef struct chartEntry{
    int id;             /* patient ID */
    CBuffptr  buffer;       /* pointer to first health type buffer */
    Chartptr  next;         /* pointer to next patient */
}Chart;


extern Chartptr patientList;   /* global declaration for start of the patient chart linked list */

我正在發送添加患者的身份證,這是我從主要人那里得到的,我知道這很有效。 但是出於某種原因,當patientList不是NULL並且它進入while循環時,它會在addPatient的其余部分中出現故障或者在while循環之后。 我不知道哪個。 謝謝你的幫助。

我想這是你的錯誤:

while(foundChart->id != patientID) {
            foundChart = foundChart->next;

您正在更新foundChart但是如果沒有patientID匹配,則永遠不會檢查while循環是否為NULL

如果找不到匹配項,則getChart()沒有條件阻止它在列表末尾運行。

請更新下面給出的代碼,它將起作用:D

Chartptr getChart(int patientID) {
    Chartptr foundChart = NULL;

    // find the patient chart with id
    foundChart = patientList;

    while(foundChart!= NULL) {
        if(foundChart->id == patientID) {
           return foundChart;
         }
        foundChart = foundChart->next;
    }

    return NULL;
 }

暫無
暫無

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

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