Instantiating a list of structs in C

18,208

Solution 1

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;

Solution 2

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.

Share:
18,208
Free Lancer
Author by

Free Lancer

I am a George Mason University Computer Science undergraduate. I like to work on web and mobile applications in the little spare time that I have. I spend my Friday nights working on class projects. That is the story of my life.

Updated on June 04, 2022

Comments

  • Free Lancer
    Free Lancer almost 2 years

    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.