【问题标题】:Singly Linked List insert function单链表插入函数
【发布时间】:2015-11-01 09:39:54
【问题描述】:

我正在尝试插入链接列表,但在调用 display() 方法时没有得到正确的输出。向链表插入数据时一切正常。

insert() 方法中的 printf 语句打印:

a int 
b int
c int

但是当调用 display() 方法时,它会打印:

c 
c
c

结构的数据类型成员根本不打印。而且,我认为 identifierName 成员每次都会被覆盖。在我对我的代码进行 sn-p 之后:

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;
    }
}

【问题讨论】:

  • 该错误很可能出现在对insert 的调用中。显示你的整个代码。
  • 在调试器下运行时发现了什么?

标签: c pointers linked-list structure


【解决方案1】:

替换这两行

newnode->next = (*headRef);
(*headRef) = newnode;

newnode->next = headRef->next;
headRef = newnode;

【讨论】:

    【解决方案2】:

    您似乎需要复制作为函数参数传递的字符串。

    按以下方式更改功能

    #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( strlen( identifier ) + 1 ); 
            strcpy( newnode->identifierName, identifier );
    

    你必须写

            newnode->identifierName = malloc( sizeof( char ) ); 
            *newnode->identifierName = *identifier;
    

    当一个节点被删除时,不要忘记释放这些指针指向的内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多