代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct node {
char* identifier;
char* expression;
struct node* next;
} node;
void add(node** database, char* _identifier, char* _expression, int * size) {
node* tmp = (node*) malloc (sizeof(node));
tmp->identifier = _identifier;
tmp->expression = _expression;
tmp->next = *database;
*database = tmp;
(*size)++;
printf("Added: %s : %s\n", _identifier, _expression); fflush(NULL);
}
void show(node* database, int size) {
if (database == NULL) {
printf("Database empty\n");
}
else {
node* tmp = database;
printf("Identifier list (%d):\n", size); fflush(NULL);
while (tmp != NULL) {
printf("%s : \"%s\" \n", tmp->identifier, tmp->expression);fflush(NULL);
tmp = tmp->next;
}
}
}
int main() {
node* database = NULL;
int size = 0;
add(&database, "a1", "abc", &size);
add(&database, "a2", "def", &size);
add(&database, "a3", "ghi", &size);
char identifier[20];
char expression[1000];
int i;
for (i = 0; i<3; i++) {
scanf("%s %s", identifier, expression);
add(&database, identifier, expression, &size);
}
show(database, size);
printf ("Bye!");
return 0;
}
“添加”函数在手动调用时效果很好,但它在循环内不起作用,数据从标准输入读取。以下是一次运行的结果:
Added: a1 : abc
Added: a2 : def
Added: a3 : ghi
a4 mno
Added: a4 : mno
a5 ghi
Added: a5 : ghi
a6 kml
Added: a6 : kml
Identifier list (6):
a6 : "kml"
a6 : "kml"
a6 : "kml"
a3 : "ghi"
a2 : "def"
a1 : "abc"
Bye!
如您所见,节点 a1、a2、a3 已正确添加到列表中。但是,a4 和 a5 在正确添加到列表后,在添加 a6 后更改为全“a6”。我已经花了一天时间,但我无法弄清楚。有人吗?