我试图插入链表,但当display()方法被调用时,我没有得到适当的输出。在向链表中插入数据时一切正常。
insert()方法中的printf语句打印:
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 %sn",newnode->identifierName,newnode->datatype); //debugging
}
void display(struct symbol* node)
{
while(node!=NULL)
{
printf("%s %sn",node->identifierName,node->datatype);
node = node->next;
}
}
似乎需要复制作为函数参数传递的字符串。
按以下方式更改函数
#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 %sn",newnode->identifierName,newnode->datatype); //debugging
}
}
考虑到函数期望形参identifier和type是指向字符串首字符的指针。
例如,如果参数标识符是指向单个字符的指针,则不用
newnode->identifierName = malloc( strlen( identifier ) + 1 );
strcpy( newnode->identifierName, identifier );
你必须写
newnode->identifierName = malloc( sizeof( char ) );
*newnode->identifierName = *identifier;
也不要忘记在删除节点时释放这些指针所指向的内存
替换这两行
newnode->next = (*headRef);
(*headRef) = newnode;
newnode->next = headRef->next;
headRef = newnode;