2013-12-14 169 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