cpointersconstants

Linked List Assignment in C: assignment discards ‘const’ qualifier from pointer target type


I was assigned a doubly linked list assignment in C and am just about done, but I can't figure out one warning that I am consistently getting. The warning is "assignment discards ‘const’ qualifier from pointer target type" and although it is just a warning, it's preventing me from properly building an executable. Here is my code:

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". */
}

This error also occurs in the functions to append and prepend a node to the list, and those functions also have const char * value as a function parameter. So it has something to do with the const char * value in the function signature. I am not allowed to change the function signatures, nor am I allowed to change the structs of List and Node which are defined in the header file and look like this:

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;

My guess is that it is happening because I am assigning const char * value to the value attribute of node, which is not constant. But I don't have any idea how I should fix this without changing the function signature or struct in some way. I'm quite new to C so any help would be much appreciated. Thank you all!


Solution

  • Based on the struct types and the signatures you're given, it looks like the struct is supposed to take ownership of the value its given. That means you'll need to make a copy of the string that's passed in (assuming that value does in fact point to a string):

    newNode->value = strdup(value); 
    

    You'll need to do the same in other functions that add to the list, and when you remove a node from the list you'll need to free the value member.