c - 当在 0 索引处打印链表值时,会出现段错误。

标签 c

//我的主要功能

int main (void) {
srandom(1);
SLL *p = newSLL(displayINTEGER,freeINTEGER);
insertSLL(p,0,newINTEGER(3));
insertSLL(p,sizeSLL(p),newINTEGER(2));
insertSLL(p,1,newINTEGER(22));

int x = getINTEGER((INTEGER *) getSLL(p,2)); //Works fine it prints 2
printf ("x is : %d\n",x); 

x = getINTEGER((INTEGER *) getSLL(p,1)); //Works fine it prints 22
printf ("x is : %d\n",x);

x = getINTEGER((INTEGER *) getSLL(p,0)); //This is where i get error (Segmentation Fault)
printf ("x is : %d\n",x);

//插入函数@param SLL,索引,值

 void insertSLL(SLL *items,int index,void *value)
    {
    SLL *newSLL = malloc(sizeof(SLL));
    newSLL->value = value;
    if (items == NULL)
            {
            }
    else if (index == 0)
            {
            newSLL->tail = items;
            items = newSLL;
            }
    else
            {
            struct sll *current = items;
            for(int i=0; i<index-1; i++)
            {
            current = current -> tail;
            }
            newSLL -> tail = current -> tail;
            current -> tail = newSLL;
            }
    }

//getSLL @param SLL 和索引并返回指向该值的指针。 //此函数在索引 > 0 时工作正常,但在索引 == 0 时出现段错误

    void *getSLL(SLL *items,int index)
    {
    int count = 0;
    while (items != NULL)
    {
            if (count == index)
            {
            return items->value;
            }
    count++;
    items = items->tail;
    }
    return NULL;
    }

最佳答案

第一个元素永远不会插入,因为 C 是按值传递的。因此,您可以更改该 insert..() 函数的局部变量。

您应该传递指针的地址或返回已分配内存的地址并将其分配给指针。

然后,需要注意的一件事是 - 在调用 insertSLL 之前,您已经动态分配了内存 - 您不需要这样做。 insert 逻辑可以这样编写,它会为第一个和中间节点执行此操作。

关于c - 当在 0 索引处打印链表值时,会出现段错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48310228/

相关文章:

c - 为什么这个代码片段可以编译?

将 "normal"矩形转换为一组 GLes vector ?

C: read() 在没有从 unix 串口获取输入的情况下挂起

c 如何使用 memcpy 将十六进制值复制到数组中

C中的自定义数据类型

c - 从数组中删除一个部分

c - 这个函数的原型(prototype)看起来如何才能可编译?

c++ - .c编程如何在客户端和服务器之间建立sip session

c++ - 有没有办法在调用 main 函数之前解析命令行选项?

c - 如何从最新的lua 5.3调用c dll