代码之家  ›  专栏  ›  技术社区  ›  Derek Kwon

C中的链表赋值:赋值将丢弃指针目标类型中的常量限定符

  •  1
  • Derek Kwon  · 技术社区  · 1 年前

    我被分配了一个C语言的双链表任务,现在就要完成了,但我无法找出一个我一直得到的警告。警告是“assignment丢弃指针目标类型中的const限定符”,尽管这只是一个警告,但它阻止了我正确构建可执行文件。这是我的代码:

    LIST *new_list(const char *value)
    {
    LIST *newList = malloc(sizeof(LIST));
    NODE *headNode = malloc(sizeof(NODE));
    headNode->previous = NULL;
    NODE *newNode = malloc(sizeof(NODE));
    NODE *tailNode = malloc(sizeof(NODE));
    tailNode->next = NULL;
    newList->head = headNode;
    newList->tail = tailNode;
    newNode->value = value; //Error occurs here
    newNode->previous = headNode;
    newList->head->next = newNode;
    newNode->next = tailNode;
    tailNode->previous = newNode;
    return newList;
    /* Create a new list and initialize its single node to "value". */
    }
    

    此错误也发生在将节点附加到列表并在列表前附加节点的函数中,并且这些函数也将const char*值作为函数参数。因此,它与函数签名中的constchar*值有关。我不允许更改函数签名,也不允许更改头文件中定义的List和Node的结构,如下所示:

    typedef struct node {
    char *value;  /* Pointer to the string we are storing. */
    struct node *previous;  /* Pointer to the preceding node in the list. */
    struct node *next;  /* Pointer to the next node in the list. */
    } NODE;
    
    typedef struct list {
    NODE *head;  /* Pointer to the first node in the list. */
    NODE *tail;  /* Pointer to the last node in the list. */
    } LIST;
    

    我的猜测是,之所以会发生这种情况,是因为我将constchar*值分配给节点的value属性,该属性不是常量。但我不知道如何在不以某种方式更改函数签名或结构的情况下解决此问题。我对C很陌生,所以如果有任何帮助,我将不胜感激。谢谢大家!

    1 回复  |  直到 1 年前
        1
  •  2
  •   dbush    1 年前

    根据结构类型和给定的签名,看起来结构应该拥有其给定值的所有权。这意味着您需要复制传入的字符串(假设 value 实际上指向字符串):

    newNode->value = strdup(value); 
    

    您需要在添加到列表中的其他函数中执行同样的操作,当您从列表中删除节点时,您需要 free 这个 价值 成员