2013-11-28 55 views
0

我有这个奇怪的分段错误。我试图找到患者列表中是否已经存在使用指针的患者列表。我认为有问题的代码是: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故障。感谢您的时间!

+0

在哪一点你有段错误?你的搜索循环条件似乎不好。 – rano

+0

[请不要在C]中输入'malloc()'的返回值(http://stackoverflow.com/a/605858/28169)。 – unwind

+0

@unwind非常感谢你!你刚刚证明我的教授。在一定程度上错误。 – user3043594

回答

2

以下代码是越野车:

while(patients_chart == NULL || patients_chart->id == patientID) { 
    patients_chart = patients_chart->next; 
    printf("here2"); 
} 

您正在推进,只要任一指针NULL或指针患者ID相匹配。你错过了否定。相反,使用:

while(patients_chart != NULL && patients_chart->id != patientID) { 
    patients_chart = patients_chart->next; 
    printf("here2"); 
} 
+0

我试过它没有解决问题。虽然,我的循环逻辑似乎没有关系。 – user3043594

+0

这解决了我的问题。但它归结为指针解引用。 – user3043594

1
while(patients_chart == NULL || patients_chart->id == patientID) { 
    patients_chart = patients_chart->next; 
} 

这里,如果条件1(patients_chart == NULL)是真实的,那么你这样做:
patients_chart = patients_chart->next;

这是空指针引用,从而导致赛格故障。

+0

就是这样! patients_chart = patientList; (patients_chart!= NULL){ while(patients_chart-> id!= patientID){ patients_chart = patients_chart-> next; } } – user3043594