簡體   English   中英

如何更改結構中的指針指向c中的值?

[英]how to change the value a pointer within a struct points to in c?

嘗試測試以下功能后,我確定注釋掉的行在嘗試運行該程序時出現段錯誤:

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

將工作

您可以使用memcpy(node_->val_, &value) ,但是目的是什么,為什么不將node_->val_聲明為int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM