-2

I try to malloc an array of structs in a different struct. Is this even possible? I searched for hours and I could not find any good explaination on how to do it properly. I want an array of "book" in "library". I need the malloc, that everything is placed on the heap and not on the stack.

struct book
{
        page *read_page;             //page is also a struct
        unsigned int id;
};

struct library
{
        book *any_book = static_cast<book*> (malloc (NBR_OF_BOOKS * sizeof(book)));

        for ( int book_counter = 0; book_counter < NBR_OF_BOOKS; book_counter++)
        {
            book[book_counter] = static_cast<book*> (malloc(sizeof(book)));
        }
        void* v = malloc(sizeof(book));
        any_book = static_cast<book*>(v);
};

I get the following error message (line 13): no match for 'operator=' (operand types are 'book' and 'book*')

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
xMutzelx
  • 566
  • 8
  • 22
  • 2
    Whatever resource you are learning from, if it taught you to write code like this, it's a horrible tutorial. Unlearn it, and then pick up an actual [good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – StoryTeller - Unslander Monica Apr 06 '17 at 09:12
  • 2
    Dude, you are writing code inside your struct declaration. Abort ! – Mohammed Bakr Sikal Apr 06 '17 at 09:14
  • @MohammedBakrSikal Sorry I am fairly new to programming and I hadn't any lessons or teacher who showed me to do it right, I try to learn it by my own and sometimes I make horrible mistakes. But instead of bashing me, a short answer like the post below would help me to impove. – xMutzelx Apr 06 '17 at 09:48

1 Answers1

1

Since this is marked c++:

const int NBR_OF_PAGES=50;
const int NBR_OF_BOOKS=20;
struct book
{
    page *read_page;             //page is also a struct
    unsigned int id;
    book(){read_page = new page[NBR_OF_PAGES];}
    ~book(){delete[] read_page;}
};

struct library 
{
    book *any_book;
    library(){any_book = new book[NBR_OF_BOOKS];}
    ~library(){delete[] any_book;}
};

edit::

Possible program:

const int NBR_OF_PAGES=50;
const int NBR_OF_BOOKS=20;
struct page{
    unsigned int id;
    unsigned int getID(){return id;}
};
struct book
{
    page *read_page;             //page is also a struct
    unsigned int id;
    book(){read_page = new page[NBR_OF_PAGES];}
    ~book(){delete[] read_page;}

};

struct library  
{
    book *any_book;
    library(){any_book = new book[NBR_OF_BOOKS];}
    ~library(){delete[] any_book;}
};
#include <iostream>
int main(){
    library lib;
    lib.any_book[3].read_page[4].id=2;
    std::cout<<lib.any_book[3].read_page[4].getID()<<std::endl;
}

Output: 2

trashy
  • 166
  • 6