gpt4 book ai didi

c - 如何更改结构体中指针指向的值?

转载 作者:行者123 更新时间:2023-11-30 15:46:12 26 4
gpt4 key购买 nike

在尝试测试以下函数后,我确定当我尝试运行程序时,注释掉的行会出现段错误:

uint8_t ll_push_front(struct List *list, int value){
if (list == NULL)
return 1;
struct ListEntry *node = (struct ListEntry *) malloc (sizeof(struct ListEntry));
if (node == NULL) exit (1);
if (list->head_ == NULL || list->tail_ == NULL || list->size_ == 0) {
list->head_ = node;
list->tail_ = node;
node->prev_ = NULL;
node->next_ = NULL;
// =====>> *(node_->val_) = value;
++(list->size_);
return 0;
}
list->head_->prev_ = node;
node->next_ = list->head_;
node->prev_ = NULL;
*(node->val_) = value;
list->head_ = node;
++(list->size_);
return 0;
}

执行*(node_->val_) = value有什么问题以及如何正确声明它?

这是结构:

struct ListEntry {
struct ListEntry * next_; // The next item in the linked list
struct ListEntry * prev_; // The next item in the linked list
int * val_; // The value for this entry
};

/* Lists consist of a chain of list entries linked between head and tail */
struct List {
struct ListEntry * head_; // Pointer to the front/head of the list
struct ListEntry * tail_; // Pointer to the end/tail of the list
unsigned size_; // The size of the list
};

这就是我初始化列表的方式:

void ll_init(struct List **list) {
*list = (struct List *) malloc (sizeof(struct List));
if (list == NULL) exit (1);
(*list)->head_ = 0;
(*list)->tail_ = 0;
(*list)->size_ = 0;
}

最佳答案

当您决定使用指向整数的指针时,您也需要对其进行malloc

struct ListEntry *node =  malloc (sizeof(struct ListEntry));

然后

node->val_  = malloc(sizeof(int));

这将使

*(node->val_) = value 

工作

或者使用

struct ListEntry {
struct ListEntry * next_; // The next item in the linked list
struct ListEntry * prev_; // The next item in the linked list
int val_; // The value for this entry (no pointer)
};

然后

node->val_ = value

可以工作

关于c - 如何更改结构体中指针指向的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18523215/

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