我的指針有問題。我正在嘗試將多個患者添加到我的列表中。我知道該怎麼做,只是代碼給了我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循環之後。我不知道哪個。謝謝你的幫助。
使用調試器或好老的printf()來找出它是怎麼了...... – John3136
不這樣的。調試器不適合我。 – user3043594