我已經嘗試了很多次將頭指標設定為指向第一個節點。起初(在空串列中)它正確地指向第一個節點。但是在第一次回圈之后,頭指標指向了鏈接的新節點。實際上,現在我對我的整個代碼也很不確定。
int main(void){
struct library *head = NULL; //set the head pointer to NULL
int option;
printf("Enter the number:");
while((option = getchar())!= 9){
switch(option){
case '1':
{
char title[1000];
char author[1000];
char subject[1000];
printf("Enter title of the book you want to add:");
scanf("%s",title);
printf("Enter author of the book you want to add:");
scanf("%s",author);
printf("Enter subject of the book you want to add:");
scanf("%s",subject);
add_book(title,author,subject,&head);
printf("successful! and head pointer is pointing to %s\n",head->collection.title);
break;
}
}
}
void add_book(char title[],char author[],char subject[], struct library ** head){
struct library *current;
struct library *newnode = malloc(sizeof(struct library));
newnode->collection.title = title;
newnode->collection.author = author;
newnode->collection.subject = subject; // assigning value inside newnode
newnode->num_books = 0;
newnode->next = NULL; // assign NULL value to the end of newnod
//when the head is NULL which means when the list is empty
if(*head == NULL)
{
current = newnode;
*head = current;
return;
}
else
{
current = *head; //assign the first node to current pointer
//find the last node of the list
while(current->next != NULL)
{
current = current->next;
}
current->next = newnode; // link the last node to new node
return;
}
}
這是為此的結構
struct book {
char* title;
char* author;
char* subject;
};
struct library {
struct book collection;
int num_books;
struct library* next;
};
uj5u.com熱心網友回復:
的壽命的char title[1000];,char author[1000];和char subject[1000];結束時執行到達的端部塊內部case '1': { /* ... */ }。一旦發生這種情況,分配給 的指標就add_book變成了懸空指標——指向無效記憶體。
為了解決這個問題,您必須確保字串的生命周期與包含它們的結構的生命周期相匹配。這可以通過在結構本身中分配足夠的空間來完成
struct book {
char title[1000];
/* etc. */
};
或者通過為每個字串的副本動態分配足夠的空間。在任何情況下,您都必須將字串復制到此記憶體 ( man 3 strcpy)。
如果它在您的系統上可用,請man 3 strdup同時執行第二種形式的兩個步驟。否則,它與 大致相同strcpy(malloc(strlen(source_string) 1), source_string);。
另請注意,說明
上一篇:通過自定義通信器發送陣列scanf符%s與不使用欄位寬度說明符(例如)時一樣危險gets,因為它可能會溢位您的緩沖區。char buffer[1000]; scanf("
