C链表指针问题

时间:2013-12-14 16:08:41

标签: c pointers struct linked-list

我正在练习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-&gt; next ;),结构的日成员的游标值设置为两个引号(“”),而不是“星期一”。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这是因为这行代码:

++cursor->ptrday;

您正在递增ptrday直到达到NULL个字符,因为C字符串是使用数组实现的,并且数组的名称等同于指向数组第一个成员的指针,当您递增指针直到达到{{ 1}}您忽略\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; } 重置为true。

答案 1 :(得分:0)

  

但为什么光标= cursor-&gt; next;声明不起作用?

它正在运行 - 但是head->next=&sunday中的作业main()创建了无限链接循环,因为*head是对象sunday然后是sunday->next回到sunday

只需删除head->next=&sunday中的main()行;您已经分配了sunday.next=&monday