所以我试图阻止以下代码中出现的段错误。它正在发生,因为我试图访问列表中尚不存在的下一个元素。我该如何防止这种情况?
while (vm->item_list.head->data !=NULL) {
printf("%-10s",vm->item_list.head->data->id);
printf("%-20s",vm->item_list.head->data->name);
printf("%-70s",vm->item_list.head->data->description);
printf("%-15d",vm->item_list.head->data->on_hand);
printf("%s","$");
printf("%d",vm->item_list.head->data->price.dollars);
printf("%s",".");
printf("%02d",vm->item_list.head->data->price.cents);
printf("\n");
vm->item_list.head = vm->item_list.head->next;
}
printf("\n");
}
答案 0 :(得分:1)
使用类似while ((vm->item_list.head != NULL ) && (vm->item_list.head->data !=NULL))
答案 1 :(得分:0)
在列表的初始化阶段,您必须声明列表的结尾,在本例中是您的下一个指针,使用NULL。如果这样做,则确保此指针不指向未定义的区域。 所以你可以这样检查:
while (vm->item_list.head->data !=NULL) {
printf("%-10s",vm->item_list.head->data->id);
printf("%-20s",vm->item_list.head->data->name);
printf("%-70s",vm->item_list.head->data->description);
printf("%-15d",vm->item_list.head->data->on_hand);
printf("%s","$");
printf("%d",vm->item_list.head->data->price.dollars);
printf("%s",".");
printf("%02d",vm->item_list.head->data->price.cents);
printf("\n");
if(vm->item_list.head->next != NULL){
vm->item_list.head = vm->item_list.head->next;
}else{
break;
}
}
或者你可以这样做:
ItemNode* node = vm->item_list.head;
while (node->data !=NULL || node->next != NULL) {
printf("%-10s",node->data->id);
printf("%-20s",node->data->name);
printf("%-70s",node->data->description);
printf("%-15d",node->data->on_hand);
printf("%s","$");
printf("%d",node->data->price.dollars);
printf("%s",".");
printf("%02d",node->data->price.cents);
printf("\n");
node = node->next;
}