我尝试在不同的结构中malloc一个结构数组。这甚至可能吗?我搜索了几个小时,我找不到任何关于如何正确做到的好解释。我想在“图书馆”中有一系列“书”。我需要malloc,所有东西都放在堆上而不是堆栈上。
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);
};
我收到以下错误消息(第13行):no match for 'operator=' (operand types are 'book' and 'book*')
答案 0 :(得分:1)
因为这标记为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;}
};
编辑::
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;
}
输出:2