[英]why am I getting out of bounds error in this linked list? C
So am making a linked list. 因此,我要制作一个链表。 printing it out. 打印出来。 and reversing it. 并扭转它。 and then printing it out. 然后将其打印出来。 first time I make it and print it out. 我第一次制作并打印出来。 everything works fine. 一切正常。 but when I reverse it. 但是当我扭转它时。 it reverses successfully. 它成功反转。 but when I print it. 但是当我打印它时。 I go out of bounds even though I use the same code I did first. 即使使用与我最初相同的代码,我也会超出范围。
Here is the reverse function 这是反向功能
void reverse_list(Node_ptr* head){
Node_ptr temp2;
Node_ptr temp3 = NULL;
temp2 = (Node_ptr)malloc(sizeof(Node));
temp3 = (Node_ptr)malloc(sizeof(Node));
if (temp2==NULL || temp3==NULL)
{
printf("Failed to allocate node\n");
exit(1);
}
while (*head!=NULL) {
temp2 = (*head)->next;
(*head)->next = temp3;
temp3 = (*head);
(*head) = temp2;
}
*head = temp3;
} }
here is the print function 这是打印功能
temp = head;
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
reverse_list(&head);
temp = head;
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
for some reason it tries to print garbage after the last element 由于某种原因,它尝试在最后一个元素之后打印垃圾
Do this: 做这个:
/* Function to reverse the linked list */
void reverse(struct node** head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
It's actually your code with a couple of fixtures, ie: 它实际上是您的代码,带有一些固定装置,即:
1) You don't need to allocate space, just swap pointers. 1)您不需要分配空间,只需交换指针。
2) Use meaningful names for your temporary containers. 2)为您的临时容器使用有意义的名称。
The first time you go through the loop 第一次经历循环
while (*head!=NULL) {
temp2 = (*head)->next;
(*head)->next = temp3;
temp3 = (*head);
(*head) = temp2;
}
(*head)->next is assigned a newly allocated node. (* head)-> next被分配了一个新分配的节点。 Who knows what this node contains? 谁知道此节点包含什么? It is probably not zeroed out, and will point to a random point in memory. 它可能没有被清零,并且将指向内存中的随机点。
You should initialize temp3 to NULL to fix this problem. 您应该将temp3初始化为NULL以解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.