我正在练习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; ),该结构的日期成员的游标值设置为两个引号(“”),而不是“星期一”。我该如何解决这个问题?
对于初学者,您在第一次不匹配时将isTrue设置为零,并且从不将其设置为代码中其他任何地方的非零值。 –
'bool'变量通常应该被赋予'false'(优先于'0')或'true'(优先于'1')。一个名叫“isTrue”的人会让脑子变得一团糟;什么是'真'?而“ptrIsTrue”更令人头脑灵活。有时你需要在'isFalse'重新署名吗?这是令人担忧的术语。 –
我同意乔纳森。我只想补充一点,定义全局变量可能会导致未来的问题,并且在全球将它们设置为“全部”程序并没有多大意义。此外,说实话,你的代码可以让你和其他人更易读,通过避免a; b; c; d; e;一切为一行的语法。 – Ervadac