[英]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.