[英]Linked List crashing, c
我的鏈表有問題。 我很確定這是我的指針被關閉了,或者因為我不熟悉c而沒有以正確的方式傳遞指針。 結構對我來說也很新,而c ++是我習慣的語言,而且差異比我所知道的還要多。 我可以立即用c ++編寫此程序,但是無論如何這是我的代碼。
void add_process(struct process new_process, struct process *head, struct process *current){
new_process.next = NULL;
if(head == NULL){
head = &new_process;
current = head;
head->next = NULL;
}
else if(new_process.timeNeeded < head->timeNeeded){
temp = head->next;
head = &new_process;
new_process.next = temp;
}
else{
current = head;
while(new_process.timeNeeded > current->timeNeeded){
temp = current;
current = current->next;
}
temp->next = &new_process;
new_process.next = current;
}
}
我正在將文件中的值讀入進程,我當前使用的唯一一個是timeNeeded,它是一個整數。 我正在嘗試在最短的時間內訂購該清單。
int main(){
FILE *readfile;
readfile = fopen("data.txt","r");
head = NULL;
current = NULL;
while(fscanf(readfile, "%s %i %i %i",
&new_process.processName, &new_process.arrivalTime,
&new_process.timeNeeded, &new_process.priority) != EOF) {
add_process(new_process, head, current);
}
current = head;
while(current->next != NULL){
printf("%s %i %i %i\n", new_process.processName, new_process.arrivalTime, new_process.timeNeeded, new_process.priority);
current = current->next;
}
return 0;
}
程序在打印時崩潰,這不是問題。 第一個問題是我的程序每次都進入if(head == NULL)循環並將其插入。 所以head可能永遠都不會改變,但我不確定如何解決,我很確定它是雙重指針,但不是肯定的。 而且我也確信還有其他問題,因此,如果您能為我指明正確的方向,並且如果我做任何完全錯誤的事情,請告訴我。
編輯:好的,所以在添加指向head的指針后,我在head-> next = NULL時遇到錯誤,說“表達式必須具有指向類的指針”。 嘗試在頭部前添加*,但似乎無濟於事。 誰知道怎么修它?
您的add_process函數在這里:
void add_process(struct process new_process,
struct process *head,
struct process *current)
接受您傳遞給by by value的任何指針。 這意味着您在while循環中調用之后:
while(fscanf(readfile, "%s %i %i %i",
&new_process.processName, &new_process.arrivalTime,
&new_process.timeNeeded, &new_process.priority) != EOF)
{
add_process(new_process, head, current);
}
head仍將為NULL,因為它從未更改過。 要讓它實際更改頭指針,而不是其他一些指針,請修改您的add_process以采用雙層指針:
void add_process(struct process new_process,
struct process **head,
struct process *current)
您上面的代碼的另一個問題是new_process
參數也被值接受。 因此,這是傳入的所有進程的臨時副本add_process
返回后, new_process
超出了作用域 。 現在,這意味着您的鏈表中有一個懸空的指針,指向無效的內存。
要解決此問題,您應該使用malloc動態分配內存,然后制作new_process的副本。 然后讓您的鏈表指向malloc
的過程。 使用malloc在堆上創建的對象將一直保留,直到被釋放。
這是一個簡單的示例,可以給您一個想法:
typedef struct process Process;
void add_process(Process new_process, Process **head, Process *current)
{
Process *new_proc_copy = (Process *)malloc( sizeof(Process) );
// now copy over the stuff from
// new_process over to this one
memcpy((char *)new_proc_copy, (char *)new_proc, sizeof(Process));
if(*head == NULL)
{
*head = new_process_copy;
current = *head;
(*head)->next = NULL;
}
else if(new_process.timeNeeded < head->timeNeeded)
{
// handle this case
}
else
{
// handle rest of your stuff
}
}
完成后不要忘記釋放已分配的內存。 這最好在您的進程清理功能中完成-C ++中的析構函數等效項只有您必須手動調用它。
似乎您沒有為new_process分配空間。 不能每次都使用相同的內存-必須分配一些內存。
還請記住,C不會自動將參數更改為通過引用。 因此,如果您想更改某些內容,則必須傳遞一個指向該內容的指針。 這包括其他指針-因此您可能需要一個指向該指針的指針。
為了能夠更改head
包含的值,必須將指向 head
的指針傳遞給add_process
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.