C 中的链表赋值:赋值从指针目标类型中丢弃“const”限定符

问题描述 投票:0回答:1

我被分配了一个 C 语言的双向链表作业,我即将完成,但我无法弄清楚我一直收到的警告。警告是“赋值从指针目标类型中丢弃‘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 * 值作为函数参数。所以它与函数签名中的 const char * 值有关。我不允许更改函数签名,也不允许更改头文件中定义的 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;

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

c pointers constants
1个回答
0
投票

根据您给出的结构类型和签名,看起来该结构应该拥有其给定值的所有权。这意味着您需要复制传入的字符串:

newNode->value = strdup(value); 

您需要在添加到列表的其他函数中执行相同的操作,并且当您从列表中删除节点时,您需要

free
value
成员。

© www.soinside.com 2019 - 2024. All rights reserved.