Reputation: 1962
Let say I have these:
typedef id Title;
typedef struct{
Title title;
int pages;
}Book;
So far, the code is okay. But the problem is here:
typedef struct{
int shelfNumber;
Book book; //How can I make this an array of Book?
}Shelf;
Like what I have stated in the comment in the code, I want to make Book as array so that it can hold a number of books. Is that even possible? If it is, how can I do it?
Upvotes: 0
Views: 2053
Reputation: 433
Note that you could use a flexible array member to achieve this effect:
typedef struct {
int shelfNumber;
size_t nbooks;
Book book[];
} Shelf;
This is an elegant use case because you have the simplicity of use of a static array but if you need to allocate a Shelf
object of size sz
, you only have to do one 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;
}
Compound literals and flexible array members that I used above are C99 features, so if you program with VC++ it might not be available.
Upvotes: 0
Reputation: 145829
typedef struct{
int shelfNumber;
Book book[10]; // Fixed number of book: 10
}Shelf;
or
typedef struct{
int shelfNumber;
Book *book; // Variable number of book
}Shelf;
in the latter case you'll have to use malloc
to allocate the array.
Upvotes: 1