0

我正在使用 C 语言编写一个简单的文本编辑器。在链接列表中插入元素时遇到问题。

这是我的结构:

 struct node {
 struct node *previous;
 int c;
 int x;
 int y;
 struct node *next;
 }*head;

这是我的插入代码:

void checker(int ch, int xpos, int ypos)
{
    int flag=0;
    struct node *temp,*temp1,*insert_node=NULL;
    temp=(struct node *)malloc(sizeof(struct node));
    temp=head;
    while(temp!=NULL)
   {
        if(temp->x==xpos && temp->y==ypos)
        {
            insert_node->c=ch;
            insert_node->x=xpos;
            insert_node->y=ypos;

            if(temp->previous==NULL) //this is for inserting at the first
            {
                   insert_node->next=temp;
                   head=insert_node;
            }

            else                     //this is for inserting in the middle.
            {
                            temp1=temp;
                temp=insert_node;
                insert_node->next=temp1;
            }

                flag=1;
                            break;
            }
                temp=temp->next;
        }

//this one's for the normal insertion and the end of the linked list.
if(flag==0)
    characters(ch,xpos,ypos);
}

第一个和中间的插入都不起作用。我不知道哪里出错了。请帮我。

4

3 回答 3

4
temp=(struct node *)malloc(sizeof(struct node));
temp=head;

您正在为一个新节点分配空间,但随后您松散了这个新节点分配的地址temp=head

于 2013-08-05T11:33:02.173 回答
1

问题是这insert_node是你的函数 checker() 中的一个局部变量,它也被初始化为 NULL。做insert_node->c意味着NULL->c我相信你会同意我的看法,这是错误的。

在使用它们之前尝试为变量动态分配内存,你应该没问题。

于 2013-08-05T11:29:53.080 回答
0

insert_node在您发布的代码中将始终为 NULL。

此外,您可能希望更多地拆分代码;首先在一个find()函数中隔离它的一部分。

于 2013-08-05T11:27:18.857 回答