C 单链表插入函数
我试图插入到链表中,但在调用display()方法时没有得到正确的输出。将数据插入链表时一切正常 insert()方法中的printf语句打印:C 单链表插入函数,c,pointers,linked-list,structure,C,Pointers,Linked List,Structure,我试图插入到链表中,但在调用display()方法时没有得到正确的输出。将数据插入链表时一切正常 insert()方法中的printf语句打印: a int b int c int 但调用display()方法时,它会打印: c c c 结构的数据类型成员根本不会被打印。而且,我认为identifierName成员每次都会被覆盖。下面是我的代码片段: struct symbol { char* identifierName; char* datatype; str
a int
b int
c int
但调用display()方法时,它会打印:
c
c
c
结构的数据类型成员根本不会被打印。而且,我认为identifierName成员每次都会被覆盖。下面是我的代码片段:
struct symbol
{
char* identifierName;
char* datatype;
struct symbol* next;
};
void insert(struct symbol** headRef,char* identifier,char* type)
{
struct symbol* newnode = (struct symbol*) malloc(sizeof(struct symbol));
newnode->identifierName = identifier;
newnode->datatype = type;
newnode->next = (*headRef);
(*headRef) = newnode;
printf("%s %s\n",newnode->identifierName,newnode->datatype); //debugging
}
void display(struct symbol* node)
{
while(node!=NULL)
{
printf("%s %s\n",node->identifierName,node->datatype);
node = node->next;
}
}
更换这两条线路
newnode->next = (*headRef);
(*headRef) = newnode;
与
似乎需要复制作为函数参数传递的字符串 按以下方式更改函数
#include <string.h>
//...
void insert(struct symbol** headRef,char* identifier,char* type)
{
struct symbol* newnode = (struct symbol*) malloc(sizeof(struct symbol));
if ( newnode )
{
newnode->identifierName = malloc( strlen( identifier ) + 1 );
strcpy( newnode->identifierName, identifier );
newnode->datatype = malloc( strlen( type ) + 1 );
strcpy( newnode->datatype, type );
newnode->next = *headRef;
*headRef = newnode;
printf("%s %s\n",newnode->identifierName,newnode->datatype); //debugging
}
}
你必须写作
newnode->identifierName = malloc( sizeof( char ) );
*newnode->identifierName = *identifier;
另外,在删除节点时,不要忘记释放这些指针指向的内存。错误最有可能出现在调用
insert
时。显示您的全部代码。在调试器下运行时,您发现了什么?
newnode->identifierName = malloc( strlen( identifier ) + 1 );
strcpy( newnode->identifierName, identifier );
newnode->identifierName = malloc( sizeof( char ) );
*newnode->identifierName = *identifier;