struct [Objective-c]中的struct数组

时间:2012-08-17 09:32:35

标签: 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作为数组,以便它可以容纳许多书。这甚至可能吗?如果是,我该怎么办?

2 个答案:

答案 0 :(得分:1)

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

typedef struct{
    int shelfNumber;
    Book *book;     // Variable number of book
 }Shelf;

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

答案 1 :(得分:0)

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

typedef struct {
    int shelfNumber;
    size_t nbooks;
    Book book[];
} Shelf;

这是一个优雅的用例,因为您可以简单地使用静态数组,但如果需要分配大小为Shelf的{​​{1}}对象,则只需要执行一个{{1} }}:

sz

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