gpt4 book ai didi

C 双向链表读访问冲突

转载 作者:行者123 更新时间:2023-11-30 15:01:21 25 4
gpt4 key购买 nike

我目前正在创建一个行星模拟,但在尝试删除相互碰撞的行星时遇到问题,请参阅下面的详细信息。

我目前在从双链表中删除元素时遇到问题,导致读取访问冲突,指出其中一个元素“为 0xFFFFFFFFFFFFFFCB”。我对 C 比较陌生,所以我相信我只是在某个地方遗漏了一些东西。

请注意,当使用remove()方法而没有destroy()方法时,不会发生该错误,只有当destroy()方法与/跟随remove()方法一起使用时才会发生该错误,并且只是偶尔发生在那。

代码附在下面:

struct planet *head; //Head of list
struct planet *tail; //Tail of list

struct planet {
//Data
float mass;
struct planet *next;
struct planet *prev;
};

planet *removeTail() {
struct planet* p = tail;
if (tail) {
if (head == tail) {
head = tail = 0;
}
else {
tail = tail->prev;
p->prev = 0;
tail->next = 0;
}
}
return p;
}

planet *removeHead() {
struct planet* p = head;
if (head) {
if (head == tail) {
head = tail = 0;
}
else {
head = head->next;
p->next = 0;
head->prev = 0;
}
}
return p;
}

planet *remove(struct planet* p) {//Breaking the tree
if (p == head) {
removeHead();
}
else if (p == tail) {
removeTail();
}
else {
p->prev->next = p->next;
p->next->prev = p->prev;
}
return p;
}

planet *destroy(struct planet* p) {
if (p) {
if (p != head || p != tail || (!p->next && p->prev)) {
delete p;
printf("Deleted\n");
return 0;
}
else {
printf("Not deleted\n");
return 0;
}
}
}

for (struct planet *p1 = head; p1 != 0; p1 = p1->next)
{
for (struct planet *p3 = head; p3 != 0; p3 = p3->next)
{
//Collision logic
if(p1 != p3){
if(p1->mass >= p3->mass){
destroy(remove(p3)); //Does not cause an error
break;
}else{
destroy(remove(p1)); //Causes the error.
break;
//Deleting p1 here means the for loop can't move on
}
}
}
}

我相信我已经包含了上面所有相关的代码,如果您需要任何进一步的信息,请告诉我。我也不知道到底是什么触发了错误,因为有时模拟可以毫无问题地删除和删除多个节点,而在其他情况下它只能删除一个节点。

如有任何建议,我们将不胜感激!

最佳答案

删除代码可以是单个函数:

planet *remove(struct planet* p)
if (p->prev == NULL) {
head = p->next;
}
else {
p->prev->next = p->next;
}

if (p->next == NULL) {
tail = p->prev;
}
else {
p->next->prev = p->prev;
}
return p;
}

也许某处应该有一个free(p)

关于C 双向链表读访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41500941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com