不能理解为什么这个段错误在c中,valgrind说错在第25行。 这是一个管理医疗工作室的程序,当病人到达时== == 1,所以它必须被添加到队列中,e == 2一个病人被访问,所以队列中的第一个元素必须被删除,当e == 0时,演播室关闭,程序必须打印病人列表,并保持按字母顺序和$。为什么在c程序中的段错误
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN (101)
typedef struct _item {
char *name;
struct _item *next;
} item;
void insert(item* tail, item* next){
item* new = (item*)malloc(sizeof(item));
new->name = (char*)malloc(MAXLEN*sizeof(char));
new->next = NULL;
scanf("%s", new->name);
if (tail == NULL){
tail = new;
next = tail;
}
else
next->next = new;
}
void examination(item *tail){
item *patient;
if (tail->next == NULL)
tail=NULL;
else{
patient = tail;
tail = tail->next;
free(patient);
}
}
int cmp(const void *a, const void *b){
return strcmp(*((char**)a) , *((char**)b));
}
int main(){
int e=1, counter=0, i=0;
item *tail = (item*)malloc(sizeof(item));
item *next;
char **remained;
tail = NULL;
next = tail;
while (e != 0){
scanf("%d", &e);
switch (e){
case 1:
insert(tail, next);
break;
case 2:
examination(tail);
case 0:
break;
default:
return 1;
}
}
next = tail;
while (next != NULL){
counter ++;
next = next->next;
}
next = tail;
remained = (char**)malloc(counter*sizeof(char*));
while(i < counter){
remained[i] = next->name;
next = next->next;
i++;
}
qsort(remained, counter, sizeof(item), cmp);
next = tail;
while (next != NULL){
printf("%s\n", next->name);
next = next->next;
}
printf("$\n");
return 0;
}
插入函数看起来不对[你需要指针指针](http://stackoverflow.com/a/18307020/1673391) – 2015-04-02 08:26:34
第25行是哪一行? – alk 2015-04-02 08:48:08
[请不要强制转换'malloc()']的结果(http://stackoverflow.com/a/605858/3233393)。 – Quentin 2015-04-02 09:33:17