//我的主要功能
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/