2013-12-14 166 views
0

我正在練習c語言,並試圖創建一個帶有結構的鏈接列表,告訴您輸入的星期幾是否在列表中。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; 
} 

(我會把掃描功能爲「enteredday,」現在它被設置到星期一。) 這個程序是隔靴搔癢最有效的一個,但我只是測試了不同的概念我已經學會了。當我使用斷點來查明程序的問題時,我發現當我嘗試將光標設置爲指向「matchtest」函數中第一個while語句結尾處的下一個結構時(cursor = cursor-> next; ),該結構的日期成員的遊標值設置爲兩個引號(「」),而不是「星期一」。我該如何解決這個問題?

+0

對於初學者,您在第一次不匹配時將isTrue設置爲零,並且從不將其設置爲代碼中其他任何地方的非零值。 –

+1

'bool'變量通常應該被賦予'false'(優先於'0')或'true'(優先於'1')。一個名叫「isTrue」的人會讓腦子變得一團糟;什麼是'真'?而「ptrIsTrue」更令人頭腦靈活。有時你需要在'isFalse'重新署名嗎?這是令人擔憂的術語。 –

+1

我同意喬納森。我只想補充一點,定義全局變量可能會導致未來的問題,並且在全球將它們設置爲「全部」程序並沒有多大意義。此外,說實話,你的代碼可以讓你和其他人更易讀,通過避免a; b; c; d; e;一切爲一行的語法。 – Ervadac

回答

2

這是因爲這行代碼:

++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。

+1

但是爲什麼光標= cursor-> next;聲明不起作用? – user3011439

0

但是爲什麼光標= cursor-> next;聲明不起作用?

據工作 - 但在main()分配head->next=&sunday創建無限的鏈接循環,因爲*head是對象sunday然後sunday->next點回sunday

只要放下head->next=&sunday一行main();你已經分配了sunday.next=&monday