我正在练习 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”添加一个扫描功能,现在它设置为星期一。) 这个程序远不是最有效的程序,但我只是在测试我已经学过的不同概念。当我使用断点来查明程序的问题时,我看到当我尝试将光标设置为指向“匹配测试”函数中第一个 while 语句末尾的下一个结构时 (cursor=cursor->next; ),结构中日期成员的游标值设置为两个引号 (""),而不是 "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。
关于C链表指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20585377/