2013-11-29 26 views
0

我的指針有問題。我正在嘗試將多個患者添加到我的列表中。我知道該怎麼做,只是代碼給了我seg故障。加入多個病人C指針

這裏是有問題的代碼:

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 */ 

我發送到外接病人,ID,這是我從主得到,那我得多知道完美的作品。 但由於某種原因,當patientList不是NULL並且它進入while循環時,它會在其餘addPatient中的seg循環或while循環之後。我不知道哪個。謝謝你的幫助。

+0

使用調試器或好老的printf()來找出它是怎麼了...... – John3136

+0

不這樣的。調試器不適合我。 – user3043594

回答

1

我覺得這裏是你的錯誤:

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

要更新foundChart但在while循環永遠不會檢查是否它已成爲NULL,萬一沒有patientID匹配。

1

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

+0

這實際上並不正確,因爲所有事情都是初始化的。 – user3043594

+0

錯誤。如果它沒有找到您要查找的ID,即使「chart-> next」爲「null」 - 即seg.fault,它也會繼續按下「chart-> next」。 – John3136

0

給出下面,將工作請更新代碼: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; 
}