0

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?

0

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is what I am looking for. So I'm going to use pointer because I need the size to be dynamic.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.