我有一个用C语言编写的程序.我很难理解我无法理解的效果.应用程序读取一系列单词作为命令行输入.在读取输入时,它将逐个单词放入列表中.然后它打印列表.让我感到震惊的是,为什么循环中添加的值正确打印,而循环中添加的值不是.我的意思是用户输入的值,只打印最后一个.此外,随着输入值的数量,它将被打印多次.两个主要的嫌疑人是push和printList方法:
void push(struct List * list, char* newValue){
assert(list != NULL);
assert(newValue != NULL);
Node* node = createNode();
node->data = newValue;
node->next = NULL;
if(list->firstNode != NULL){
node->next = list->firstNode;
list->firstNode = node;
}
else list->firstNode = node;
}
void printList(struct List * list){
assert(list != NULL);
Node *node = list->firstNode;
while(node->next != NULL){
printf("%s ", node->data);
node = node->next;
}
if(node != NULL) printf("%s ", node->data);
}
Run Code Online (Sandbox Code Playgroud)
但我找不到任何错误.我做的是比较有和没有while循环的行为:
int main(){
struct List* list = createList();
char s[256];
int a;
push(list, "he");
push(list, "bee");
push(list, "gee");
while(scanf("%s", &s) == 1) push(list, s);
printList(list);
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
ccc gee bee他
虽然输入是:
ABC
所以我期待得到
cba gee bee他
我错过了什么?任何建议都非常感谢.
PS上面使用的类型defs和方法是:
typedef struct Node {
char* data;
struct Node *next;
} Node;
typedef struct List {
struct Node *firstNode;
} List;
Node *createNode(){
Node* node = malloc(sizeof(struct Node));
assert(node != NULL);
node->data = "";
node->next = NULL;
return node;
}
List *createList(){
List* list = malloc(sizeof(struct List));
list->firstNode = NULL;
assert(list != NULL);
return list;
}
Run Code Online (Sandbox Code Playgroud)
while(scanf("%s", &s) == 1) push(list, s);
Run Code Online (Sandbox Code Playgroud)
每当你打电话给push你时,你都会s进入清单.因此,每个条目都将包含完全相同的指针值,这可能不是您想要的.
当你去打印时,s包含"c".每个节点都有一个指向s,所以你打印"c"三次,每个节点一次.