gpt4 book ai didi

追加函数中的 C 指针不更新头尾的值

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:33 25 4
gpt4 key购买 nike

创建了一个函数,它接受一个 List Struct 指针和一个 double 值,该值是将要存储在链表中的数据。当我调用函数来添加值时,它们被存储为头部和尾部,并且之前的值没有被保存。

列表结构:

typedef struct LIST_{
int size;

int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);

ListElmt *head;
ListElmt *tail;
}List;

list_init 函数:

void list_init(List *pPolynomial, void (*destroy)(void *data)){
pPolynomial->size = 0;
pPolynomial->destroy = destroy;
pPolynomial->head = NULL;
pPolynomial->tail = NULL;

}

附加项函数:

List* appendTerm(List *pPolynomial, double constant){
//inserting value at the end of the list
ListElmt *element;
element = (ListElmt *)malloc(sizeof(ListElmt));
double* d = &constant;
element->data = d;

if(pPolynomial->size == 0){
//if there was no head
pPolynomial->head = element;
pPolynomial->tail = element;
element->next = NULL;
printf("This is the data stored in the head %f \n", *(double*)pPolynomial->head->data);
printf("This is the data stored in the tail %f \n", *(double*)pPolynomial->tail->data);
}
else{
//there is a head
pPolynomial->tail = pPolynomial->tail->next;
pPolynomial->tail->next = element;

element->next = NULL;
printf("else statement: This is the data still stored in the head %f \n", *(double*)pPolynomial->head->data);
printf("This is the data stored in the tail %f \n", *(double*)pPolynomial->tail->data);
}
pPolynomial->size++;
printf("size: %d\n", pPolynomial->size);

return pPolynomial;
}



int main() {
List* listOfInts;
ListElmt *pElmt;
double *pDbl;
int i;


list_init(listOfInts, free);
listOfInts = appendTerm(listOfInts, 5);
listOfInts = appendTerm(listOfInts,6);
listOfInts = appendTerm(listOfInts,7);

pElmt = listOfInts->head;
for (int i = 0; i < 3; i++)
{
double d = *(double *) pElmt->data;
printf("List elem %d = %f\n", i, d);
pElmt = pElmt->next;
}


return (EXIT_SUCCESS);
}

这是程序的输出:

This is the data stored in the head 5.000000 
This is the data stored in the tail 5.000000
size: 1
else statement: This is the data still stored in the head 6.000000
This is the data stored in the tail 6.000000
size: 2
else statement: This is the data still stored in the head 7.000000
This is the data stored in the tail 7.000000
size: 3
List elem 0 = 7.000000
List elem 1 = 0.000000
List elem 2 = 0.000000

最佳答案

无需在列表中存储指向 double 的指针。只是存储双。存储指针的问题在于管理它。在您的例子中,您在结构中存储了一个指向局部变量的指针:

double* d = &constant;
element->data = d;

一旦 appendTerm 函数返回,this 指针指向的变量就超出了作用域,指针悬空,导致在取消引用时出现未定义行为。

这个(在您的测试中)的最终结果是所有节点都指向相同的内存位置,该位置(在您打印列表内容时)仍然保存列表中存储的最后一个值。

解决方案是将 double 值存储在 ListElmt 而不是指针中。如果您必须存储指针,则需要malloc 空间来保存它(并在删除节点时释放该空间)。

关于追加函数中的 C 指针不更新头尾的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57086947/

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