简体   繁体   中英

Global variable Linked Lists queue in C? (Initializer element is not constant)

I am working on a project involving a series of Queues. These Queues are intended to be Global in scope as they are handled and modified by a series of functions. As of right now, my implementation raises the "Initializer element is not constant" flag. I understand why, for the most part, but I was wondering if there is an alternative way to achieve this. (ie. An array containing each Queue?) Is this possible?

main.c

LIST* queue0 = ListCreate();  //0
LIST* queue1 = ListCreate();   //1
LIST* queue2 = ListCreate();   //2

int main(){......}

ListCreate occurs as follows:

implement.c

LIST *ListCreate()
{
    int popped = popList();
    if (popped != -1){
        //Create list
        lists[popped].currSize = 0;
        return &lists[popped];
    }
    else{
        return NULL;
    }
}

(Bear in mind, I was required to build a Linked List without the use of malloc.)

LIST* queue0 = NULL;
LIST* queue1 = NULL;
LIST* queue2 = NULL;

void initQueues(void) {
    queue0 = ListCreate();
    queue1 = ListCreate();
    queue2 = ListCreate();
}

void main(int argc, char *argv[]) {
    initQueues();
    // ... (i.e. other stuff)

}

You don't actually need dynamic allocation for linked lists. You can put them in global (or static) memory, but you'll have to initilise them manually, which is doable for small lists (Note: the initialiser values are all constant, or at least computable at compile time). Example:


struct llist {
        struct llist *next;
        // Whatever
        char *payload;
        };

struct llist lists[] =
{{ lists+1, "one" }
,{ lists+2, "two" }
,{ lists+3, "three" }
,{ lists+4, "four" }
,{ lists+5, "five" }
,{ lists+6, "six" }
,{ lists+7, "seven" }
,{ lists+8, "eight" }
,{ lists+9, "nine" }
,{ NULL, "ten" }
        };

struct llist *freelist = lists;
struct llist *queue = NULL;

        /* example for constructor / destructor */
struct llist *newnode (void)
{
struct llist *this ;
this = freelist;
if (this) freelist = this->next;
return this;
}

void freenode (struct llist *ptr)
{
if (!ptr) return;
ptr->next = freelist;
freelist= ptr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM