谁能检查我的链表实现是否有错误?尝试遍历链表时,我不断遇到段错误。
我正在尝试从“process_command”中的“root”遍历链表,但是当我尝试访问 root->child 时,我会收到 seg 错误错误。
节点的实现
typedef struct _node {
struct _node *child;
char *command;
} Command_list;
我用来标记字符串并将它们放入链接列表的两个函数。
Command_list *process_command( char command_line[256] )
{
printf("Command: %s", command_line);
//allocate space for root & child
Command_list *root = (Command_list*)malloc(sizeof (Command_list));
Command_list *child = (Command_list*)malloc(sizeof (Command_list));
char *token;
char *saveptr;
//get the first part of the string
token = strtok_r( command_line, " ", &saveptr);
//if the first word in the string is student
if( !strcmp(token, "student") )
{
//set the first word to the be root
root = insert_command( token, root );
printf("Current root command: %s \n", root->command);
child = root;
//get the next word from the string
token = strtok_r( NULL, " ", &saveptr);
//keep getting words from the list and store them in a linked-list
while( token != NULL )
{
child = insert_command( token, child );
token = strtok_r( NULL, " ", &saveptr);
}
}
return root;
}
Command_list *insert_command( char *value, Command_list *root)
{
printf("previous value: %s \n", root->command);
Command_list *child_node = (Command_list*)malloc(sizeof (Command_list));
//if the node being passed in is empty, store the value in itself
if( root->command == NULL ){
root->command = value;
root->child = 0;
printf("Inserting value to root: %s \n", root->command);
return root;
}
//otherwise store the value in a child node
else
{
child_node->command = value;
child_node->child = 0;
printf("Inserting value to child node: %s \n", child_node->command);
return child_node;
}
}
编辑: 迭代代码
{
....
Command_list *temp = (Command_list*)malloc(sizeof (Command_list));
temp = root;
while(temp != NULL){
printf("Command: %s\n", temp->command);
temp = temp->child;
....
}
添加了我正在使用的迭代代码。该代码似乎在代码块中运行良好,但在终端中的第一个输出后停止迭代。