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.
但它不工作。非常感谢您的帮助。
2 个解决方案
#1
3
If create_lock()
returns a pointer to a lock
, the following should work:
如果create_lock()返回一个指向锁的指针,则应执行以下操作:
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:
typedef struct lock lock;
#2
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.
然后,您可以使用一个lockList实例来存储一个动态大小的锁列表。
#1
3
If create_lock()
returns a pointer to a lock
, the following should work:
如果create_lock()返回一个指向锁的指针,则应执行以下操作:
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:
typedef struct lock lock;
#2
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.
然后,您可以使用一个lockList实例来存储一个动态大小的锁列表。