typedef struct _node{
int count;
char * command;
struct _node * next;
}Node;
typedef struct _list{
Node * head;
Node * cur;
Node * tail;
}List;
List * history;
void list_init()
{
history = (List*)malloc(sizeof(history));
history->head = history->cur = history->tail = NULL;
}
char * copy_command(char * command, int len)
{
char * temp_command = (char*)malloc(sizeof(char)*(len+1));
strncpy(temp_command, command, len+1);
return temp_command;
}
void insert_history(int cnt, char * command)
{
Node * temp = (Node*)malloc(sizeof(Node));
temp->count = cnt;
temp->command = command;
temp->next = NULL;
if(history->head == NULL){
printf("hello %s\n", command);
history->head = temp;
printf("hello2 %s\n", temp->command);
}
else
history->cur->next = temp;
printf("head hello %s\n", history->head->command);
history->cur = temp;
history->tail = temp;
}
void print_history()
{
history->cur = history->head;
printf("history head: %s | ", history->head->command);
while(history->cur != NULL){
printf("%-3d %s\n", history->cur->count, history->cur->command);
history->cur = history->cur->next;
}
history->cur = history->tail;
}
大家好。 当我打电话给这个时,
char str[30] = "history";
list_init();
cur_command = copy_command(str, strlen(str))
insert_history(1, cur_command);
print_history();
我得到了
你好历史
hello2历史
你好历史记 历史负责人:�& @��| 1�& @��
history是一个全局值,包含指向节点的指针
我在insert_history()函数中打印history-> head->命令时没关系,
但是当我在print_history()函数中打印history-> head->命令时,它不行
当我拨打上面的代码两次时,它按照我的预期工作
但是当我第一次打电话时它不起作用。
我不知道该怎么做。