结构[Objective-c]中的结构数组

结构[Objective-c]中的结构数组,objective-c,ios,c,arrays,struct,Objective C,Ios,C,Arrays,Struct,假设我有这些: typedef id Title; typedef struct{ Title title; int pages; }Book; 到目前为止,代码还可以。但问题在于: typedef struct{ int shelfNumber; Book book; //How can I make this an array of Book? }Shelf; 就像我在代码中的注释中所说的,我希望将Book设置为数组,这样它就可以容纳许多书籍。这可能吗?

假设我有这些:

typedef id Title;

typedef struct{
    Title title;
    int pages;
}Book;
到目前为止,代码还可以。但问题在于:

typedef struct{
   int shelfNumber;
   Book book;   //How can I make this an array of Book?
}Shelf;
就像我在代码中的注释中所说的,我希望将Book设置为数组,这样它就可以容纳许多书籍。这可能吗?如果是,我怎么做

typedef struct{
    int shelfNumber;
    Book book[10];   // Fixed number of book: 10
 }Shelf;

在后一种情况下,您必须使用
malloc
来分配数组。

请注意,您可以使用来实现此效果:

typedef struct {
    int shelfNumber;
    size_t nbooks;
    Book book[];
} Shelf;
这是一个优雅的用例,因为您可以简单地使用静态数组,但是如果您需要分配一个大小为
sz
Shelf
对象,您只需执行一个
malloc

Shelf *mkShelf(int num, size_t sz) {
    Shelf *s = malloc(sizeof(Shelf) + sz * sizeof(Book));
    if (!s) return NULL;
    *s = (Shelf){ num, sz };
    return s;
}

我上面使用的复合文字和灵活的数组成员是C99的特性,因此如果您使用VC++编程,它可能不可用。

谢谢!这就是我要找的。所以我将使用指针,因为我需要动态的大小。
Shelf *mkShelf(int num, size_t sz) {
    Shelf *s = malloc(sizeof(Shelf) + sz * sizeof(Book));
    if (!s) return NULL;
    *s = (Shelf){ num, sz };
    return s;
}