【发布时间】:2019-04-13 16:03:19
【问题描述】:
typedef struct NODE{
char *word;
struct NODE *next;
}node;
node *newNode(char *word) {
node *pNode = (node*) malloc(sizeof(node));
pNode->word = word;
pNode->next = NULL;
return pNode;
}
void append(node **ppList, char *word) {
if(*ppList == NULL)
*ppList = newNode(word);
else {
node *tmpList = *ppList;
for(; tmpList->next!=NULL; tmpList=tmpList->next);
tmpList->next = newNode(word);
}
}
void printList(node *list) {
for(; list!=NULL; list=list->next)
printf("[%s]=>", list->word);
printf("NULL");
}
/*=== CODE 1 ===*/
int main() {
char word[MAXCHAR], word2[MAXCHAR], word3[MAXCHAR];
node *list=NULL;
scanf("%s", &word); /* key in AAA */
append(&list, word);
scanf("%s", &word2); /* key in BBB */
append(&list, word2);
scanf("%s", &word3); /* key in CCC */
append(&list, word3);
printList(list);
return 0;
}
/*=== CODE 2 ===*/
int main() {
char word[MAXCHAR];
node *list=NULL;
scanf("%s", &word); /* key in AAA */
append(&list, word);
scanf("%s", &word); /* key in BBB */
append(&list, word);
scanf("%s", &word); /* key in CCC */
append(&list, word);
printList(list);
return 0;
}
输出:
=== CODE 1 OUTPUT ===
[AAA]=>[BBB]=>[CCC]=>NULL /* it works */
=== CODE 2 OUTPUT ===
[CCC]=>[CCC]=>[CCC]=>NULL /* doesnt work, why? */
嗨,我正在尝试循环这个东西,然后我意识到它得到了错误的结果。我隔离了我的程序,我发现输入是问题,我尝试了 scanf 并且两者都不起作用。为什么我不能使用 char 数组来存储输入,有人可以帮我解决这个问题。
【问题讨论】:
-
需要说明
append函数是如何定义的,请提供minimal reproducible example。 -
scanf("%s", &word);而不是这个,试试这个:scanf("%s", word); -
投票关闭,因为不清楚你在问什么。请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅“如何提问”页面以获得澄清此问题的帮助。
标签: c arrays input linked-list char