如何更改c中结构中指针指向的值?
在尝试测试以下功能后,我确定当我尝试运行程序时,注释掉的线路出现seg故障:如何更改c中结构中指针指向的值?,c,pointers,struct,linked-list,segmentation-fault,C,Pointers,Struct,Linked List,Segmentation Fault,在尝试测试以下功能后,我确定当我尝试运行程序时,注释掉的线路出现seg故障: 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
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;
}
您可以使用
memcpy(node->val->value)
,但是您的目的是什么,为什么不将node->val->/code>声明为int
,因为您已经决定使用指向整数的指针,您也需要malloc
i、 e
然后
这将使
*(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)
};
然后
将工作如何声明节点
以及在何处设置?需要知道如何定义结构如果val是int,则应该执行节点->val=value
您的val
成员是int
指针(int*
)。你给它分配了一些内存吗?我看到的代码没有。实际上,它似乎在使用节点级别malloc()
之后指针中的任何值。这称为不确定指针,将其用于求值或赋值是未定义的行为。最后,我不明白为什么它首先是一个指针。看起来一个普通的int
就足够了。如果你使用一个指向val的指针,那么你必须在赋值之前检查这个指针,我想。
*(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