[英]C linked list pointer issue
我正在練習c語言,我正在嘗試創建一個鏈接列表,其中的結構告訴您輸入的星期幾是否在列表中。
#include <stdio.h>
#include <stdbool.h>
bool isTrue=1, *ptrisTrue=&isTrue;
struct weekday {
char *ptrday;
struct weekday *next;
} sunday, monday, tuesday, wednesday, thursday, friday, saturday;
struct weekday *head=&sunday;
struct weekday *cursor;
struct weekday *ecursor;
void matchtest(char *eday, struct weekday *head, struct weekday *cursor) {
cursor=head;
while (cursor!=(struct weekday *)0){
while (*eday!='\0') {
if (*eday!=*cursor->ptrday)
*ptrisTrue=0;
++eday; ++cursor->ptrday;
}
if (*ptrisTrue==1)
printf("Yes, %s is in the list\n", cursor->ptrday);
cursor=cursor->next;
}
}
int main (void) {
char enteredday[]="Monday", *ptreday=enteredday;
sunday.ptrday="Sunday"; monday.ptrday="Monday"; tuesday.ptrday="Tuesday";
wednesday.ptrday="Wednesday"; thursday.ptrday="Thursday";
friday.ptrday="Friday"; saturday.ptrday="Saturday";
sunday.next=&monday; monday.next=&tuesday; tuesday.next=&wednesday;
wednesday.next=&thursday; thursday.next=&friday; friday.next=&saturday;
saturday.next=(struct weekday *)0;
head->next=&sunday;
printf("This is a test to see if a day is in the list.\n");
matchtest(ptreday, head, cursor);
return 0;
}
(我將為“enterday”設置一個掃描功能,現在設置為星期一。)這個程序遠不是最有效的程序,但我只是測試了我已經學過的不同概念。 當我使用斷點來查明程序的問題時,我看到當我嘗試將光標設置為指向“matchtest”函數中第一個while語句末尾的下一個結構時(cursor = cursor-> next; ),結構的day成員的游標值設置為兩個引號(“”),而不是“Monday”。 我該如何解決這個問題?
這是因為這行代碼:
++cursor->ptrday;
您正在遞增ptrday直到達到NULL
字符,因為C字符串是使用數組實現的,並且數組的名稱等同於指向數組的第一個成員的指針,當您遞增指針直到達到\\0
您將忽略\\0
之前的所有字符。
記憶是這樣的:
_______________
|M|o|n|d|a|y|\0|
________________
^ Where cursor->ptrday used to and should point to,
^ Where cursor->ptrday points to after the second while statement
要解決這個問題,您可以使用strcmp
函數或更改while
循環,如下所示:
char* p = cursor->ptrday;
*ptrisTrue = 1;
while (*eday!='\0') {
if (*eday != *p)
*ptrisTrue=0;
++eday; ++p;
}
另請注意,您忘記將*ptrisTrue
重置為true。
但是為什么cursor = cursor-> next; 聲明不起作用?
它正在工作 - 但是通過賦值head->next=&sunday
in main()
你創建了一個無限的鏈接循環,因為*head
是sunday
的對象,然后是sunday->next
指向sunday
。
只需在main()
刪除head->next=&sunday
line; 你已經分配了sunday.next=&monday
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.