给定数据结构
#define DATASTRUCTURE_H
#define MAXINDEX 307
typedef enum {So, Mo, Di, Mi, Do, Fr, Sa} eDayofTheWeek;
typedef struct{
int Day;
int Month;
int Year;
eDayofTheWeek WeekDay;
} sDate;
typedef struct{
int Hour;
int Minute;
int Second;
}sTime;
typedef struct sALE{
sDate Date;
sTime Time;
char *Description;
char *Location;
sTime Lenght;
struct sALE *Next;
struct sALE *Prev;
int ID;
}sAppointment;
typedef struct sLE{
sAppointment *Appointment;
struct sLE *Next;
}sListEntry;
typedef struct{
sListEntry *first;
sListEntry *last;
}sHashEntry;
extern sHashEntry AppIndex[MAXINDEX];
extern sAppointment *First, *Last;
#endif
将用于在此函数中创建与 sListElement 的约会
sListEntry *Create = malloc(sizeof(sListEntry));
if(Create != NULL){
enter(1);
printf("Termin erstellen");
enter(2);
if(getDate("Datum: ", &(Create->Appointment->Date))){
if(getTime("Uhrzeit[Std:Min]: ", &(Create->Appointment->Time))){
if(getDuration("Dauer[Std:Min:Sek]: ", &(Create->Appointment->Lenght))){
if(getText("Terminbeschreibung: ", 100, &(Create->Appointment->Description), 0)){
if(getText("Ort: ", 15, &(Create->Appointment->Location), 1))
check = 1;
}
}
}
}
当我键入输入后出现
getDuration
时,就会发生分段错误:
int getDuration(char *prompt, sTime *time){
char in[20];
int Len;
do{
printf(prompt);
scanf("%[^\n]", in);
clearBuffer();
Len = strlen(in);
}while(!(getTimeFromStringLite(in, time)) && (Len != 0));
return 1;
}
(
getDuration
要求用户以小时:分钟:秒格式输入并将其添加到数据结构中,也允许用户在其中不进行任何输入)
为什么会这样?
当我执行相同的代码但使用数据类型
sAppointment
(现在包含在 sListEntry
中)时,它可以工作,但由于我更改了数据类型并调整了变量,因此出现了分段错误。变量是唯一改变的。所有其他功能保持不变。
引用评论:“看起来您没有为创建->约会分配空间,因此一旦您创建->约会->,您就会取消引用未初始化的指针,从而调用未定义的行为。”