我有这个奇怪的分段错误。我试图找到患者列表中是否已经存在使用指针的患者列表。我认为有问题的代码是:C指针分割错误
#include <stdio.h>
#include <stdlib.h>
#include "health.h"
void addPatient(int patientID) {
printf("here1");
Chart* patients_chart;
// find the patient with id
patients_chart = patientList;
while(patients_chart == NULL || patients_chart->id == patientID) {
patients_chart = patients_chart->next;
printf("here2");
}
printf("here3");
// if patient wasn't found, add new patient
if (patients_chart == NULL) {
Chart *new_chart;
printf("here4");
// allocate and initialize new patient
new_chart = (Chart*)malloc(sizeof(Chart));
new_chart->id = patientID;
new_chart->buffer = NULL;
// insert new patient into list
new_chart->next = patientList;
patientList = new_chart;
printf("here5");
}
}
包含的health.h只是方法声明和结构。我将在下面列出它们,但请注意,我的任务限制了我修改health.h中的任何代码。我也会在最后发布我的代码。
/*
* 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;
我调用该函数在主与输入像这样的:1,12:12:12,7,0
的7设置在 “命令”
1是患者有问题的ID
您可以忽略其余。
我明白如何找到病人,但我得到这个令人讨厌的seg故障。感谢您的时间!
在哪一点你有段错误?你的搜索循环条件似乎不好。 – rano
[请不要在C]中输入'malloc()'的返回值(http://stackoverflow.com/a/605858/28169)。 – unwind
@unwind非常感谢你!你刚刚证明我的教授。在一定程度上错误。 – user3043594