這可能是一個愚蠢的問題,但基本上這個程式使用指標串列但在第一次使用我showliste用來列印串列的函式后停止執行,我不知道為什么。如果我洗掉該showliste函式,那么它會很好地運行其余代碼,但是我真的不知道為什么,因為我沒有修改該函式中的任何內容,它的唯一目的是列印出元素。
如果有人可以幫助我,那將非常有用。先感謝您!
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 10
struct book{
char name[50];
float price;
struct book *next;
};
typedef struct book BOOK;
BOOK * createlist(BOOK *);
void showliste(BOOK *);
BOOK * deleteElem(BOOK *);
int main()
{
BOOK *pstart = NULL;
pstart = createlist(pstart);
printf("\nHere is the ordered list: \n");
showliste(pstart); //stops excution after this for some reason
pstart = deleteElem(pstart);
printf("\nHere is the list with the element deleted: \n");
showliste(pstart);
return 0;
}
BOOK * createlist(BOOK *pdebut)
{
int i, choice = 0;
BOOK *pparcour = NULL, *pprecedent = NULL, *pnew = NULL;
for(i = 0; i < max && choice == 0; i )
{
pnew = (BOOK *)malloc(sizeof(BOOK));
printf("Enter name: ");
fflush(stdin);
gets(pnew->name);
printf("Enter Price: ");
scanf("%f", &pnew->price);
if(pdebut == NULL)
{
pdebut = pnew;
}
else{
pparcour = pdebut;
pprecedent = NULL;
while(pparcour != NULL && pnew->price > pparcour->price)
{
pprecedent = pparcour;
pparcour = pparcour->next;
}
if(pprecedent == NULL)
{
pnew->next = pparcour;
pdebut = pnew;
}
else{
pprecedent->next = pnew;
pnew->next = pparcour;
}
}
printf("Do you want to continue? \n");
printf("0 - Yes 1 - NO\n");
printf("Choice: ");
scanf("%d", &choice);
}
return pdebut;
}
void showliste(BOOK *pdebut)
{
while(pdebut != NULL)
{
printf("Name: %s\n", pdebut->name);
printf("Price: %.3f\n\n", pdebut->price);
pdebut = pdebut->next;
}
}
BOOK * deleteElem(BOOK *pdebut)
{
char cible[50];
BOOK *pprecedent = NULL, *pparcour = NULL;
printf("Enter the name of the book you want to delete: ");
fflush(stdin);
gets(cible);
pparcour = pdebut;
pprecedent = NULL;
while(pparcour != NULL && strcmpi(cible, pparcour->name))
{
pprecedent = pparcour;
pparcour = pparcour->next;
}
if(pparcour == NULL)
{
printf("\nEntered name is not in the list!!!!\n");
}
else{
if(pprecedent == NULL)
{
pdebut = pdebut->next;
free(pparcour);
}
else{
pprecedent->next = pparcour->next;
free(pparcour);
}
}
return pdebut;
}
pdebut是串列的頭部。pparcour是一個指標,我用它來瀏覽我的串列而不修改它。pprecedent基本上就是之前的元素pparcour,主要用于在有序串列的正確位置添加一本新書(如果新書的價格小于位于的價格pparcour->price)
uj5u.com熱心網友回復:
這些行
pparcour = pdebut;
/* ... */
pparcour = pparcour->next;
設定對最近 'd 結構的未初始化next成員的訪問malloc,其中包含不確定的指標值。試圖price通過這個不確定的指標值讀取成員
while(pparcour != NULL && pnew->price > pparcour->price)
將在回圈的后續迭代中呼叫未定義行為。
使用calloc,或手動將新分配的節點的next成員設定為NULL。
for(i = 0; i < max && choice == 0; i )
{
pnew = malloc(sizeof *pnew);
pnew->next = NULL;
/* ... */
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485117.html
標籤:C
上一篇:我正在嘗試使用int從藍牙向ArduinoESP32輸入一個值,但該值被讀取錯誤,
下一篇:系統呼叫讀取結果后顯示隨機字符
