Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a list of structs in C

I'm sure this must have been asked before but I can't seem to find an answer anywhere. I have a struct defined in a header file as so:

struct lock {
    char *name;
    // add what you need here
    void *holder;
    // (don't forget to mark things volatile as needed)
};

I want to make a list of lock objects. That way I can say something like:

lock_list[0] = create_lock();
lock_list[1] = create_lock();

I tried different ways but they all give me errors. I thought I could simply say:

lock[2] lock_list;

but it didn't work. Any help would be much appreciated.

like image 237
Free Lancer Avatar asked Nov 01 '11 19:11

Free Lancer


2 Answers

If create_lock() returns a pointer to a lock, the following should work:

lock *lock_list[2];

Also, since you didn't post it, you need to typedef your struct if you want to be able to omit the struct part when using it:

typedef struct lock lock;
like image 133
Tim Cooper Avatar answered Sep 28 '22 07:09

Tim Cooper


If it's not fixed size, you can produce a linked list:

typedef struct lock_t lock;
typedef struct lockList_t lockList;

struct lock_t {
    char *name;
    void *holder;
}

struct lockList_t {
    lock lock_entry;
    lockList *lock_next;
}

You can then use an instance of lockList to store a dynamically sized list of locks.

like image 36
Polynomial Avatar answered Sep 28 '22 09:09

Polynomial