0

I'm working with structures in C where I've defined a doubly linked list and a function to add elements to the left of the list (list_add_left). The problem I'm facing is that I only have the name of the doubly linked list I want to add to, but the list_add_left function takes a doubly linked list as its first argument and not strings.

Here are my structure and function definitions:

List* list_init(char attribute) {
    List* new_list = (List*)malloc(sizeof(List));
    if (new_list != NULL) {
        new_list->size = 0;
        new_list->attribute = attribute;
        new_list->first = NULL;
        new_list->last = NULL;
    }
    return new_list;
}

void list_add_left(List* list, const char* color, const char* shape) {
    Node* new_node = create_node(color, shape);
    if (new_node != NULL) {
        if (list->size == 0) {
            list->first = new_node;
            list->last = new_node;
        } else {
            new_node->next = list->first;
            list->first->prev = new_node;
            list->first = new_node;
        }
        list->size++;
    }
}

I've also created instances of the List:

List* listRed = list_init('Red');
List* listYellow = list_init('Yellow');
List* listGreen = list_init('Green');
List* listBlue = list_init('Blue');

Now, if I want to add to listRed, how should I use the list_add_left function when I only have the string listRed?

I've tried the dereferencing operator (*), but it did not work. I also attempted (void)&listRed, but that did not work either.

Any suggestions on how I can achieve this?

3
  • List* LookupListByName(const char* listname)) { if (strcmp(listname, "listRed")==0) { return &listRed; } ... else return NULL; } -- you need to manually add each list. You could also build some kind of map(string, pointer) struct and add to it each time you create a new list. Commented Jan 27, 2024 at 3:25
  • do you mean list_add_left( listRed, "foo", "bar" ); ? Commented Jan 27, 2024 at 3:29
  • char means a single character -- your attempt to pass 'Yellow' to list_init will not behave as expected Commented Jan 27, 2024 at 3:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.