enum ev_type { ARRIVAL, DEP_Q0, DEP_Q1, DEP_Q2, DEP_Q3 };
struct node {
double time;
double duration;
enum ev_type event;
struct node * next;
}*evlist;
typedef struct node *nptr;
double min = 0;
void generate_new_customer(double clock, double duration)
{
nptr newev = (nptr)malloc(sizeof(nptr));
newev->duration = duration;
newev->time = min;
newev->event = ARRIVAL;
if (evlist == NULL)
{
evlist = newev;
evlist->next = NULL;
}
else
{
newev->next = evlist;
evlist = newev;
}
printf("%lf\n", evlist->time);
}
int main() {
start();
while (1) {
generate_new_customer(1, 6);
if (min > 480)
break;
min++;
}
return 0;
}
我正在尝试使用功能进行内存分配。该函数按最小值工作。如果最小值增加480,它将停止并中断。我检查了但是仍然会发生调试断言失败的错误。我该怎么办?
答案 0 :(得分:1)
您的malloc
不正确。只是在需要 pointer 的大小时才将其分配给您的结构。
更改:
nptr newev = (nptr) malloc(sizeof(nptr));
进入:
nptr newev = malloc(sizeof(struct node));
更新:
我注意到您的功能正在将您的列表推到最前面。这不是错误,但是您可以简化一下:
您的原始代码:
if (evlist == NULL) {
evlist = newev;
evlist->next = NULL;
}
else {
newev->next = evlist;
evlist = newev;
}
轻微的重新排序:
if (evlist == NULL) {
evlist = newev;
newev->next = NULL;
}
else {
newev->next = evlist;
evlist = newev;
}
一些重新排序:
if (evlist == NULL) {
newev->next = NULL;
evlist = newev;
}
else {
newev->next = evlist;
evlist = newev;
}
由于newev->next = NULL
在if
被保证为evlist
的{{1}}子句的NULL
内,我们可以将其更改为:
if (evlist == NULL) {
newev->next = evlist;
evlist = newev;
}
else {
newev->next = evlist;
evlist = newev;
}
现在,if
和else
都是相同的。因此,我们可以消除冗余,并且有:
newev->next = evlist;
evlist = newev;