我有以下的东西,
struct CandyBar{
std::string name;
double weight;
int calories;
} ;
现在,创建一个包含许多CandyBars的结构体数组非常简单,我已经像这样完成了;
int main(){
CandyBar bars[] = {{"Mango tart", 2.3, 100}, {"Yo Yo", 3.2, 130}, {"Orange Ball", 1.7, 98}};
return 0;
}
但是,现在我想使用新的方式创建相同的结构。当我想到这个时很简单,但是它却崩溃了并且无法工作。
CandyBar *bars = new CandyBar;
(*bars).name = "Mango tart";
bars->weight = 2.3;
bars->calories = 100;
bars += 1;
(*bars).name = "Yo Yo";
bars->weight = 3.2;
bars->calories = 130;
bars += 1;
(*bars).name = "Orange Ball";
bars->weight = 1.7;
bars->calories = 98;
但是,这并不起作用。我认为第一个指针是指向第一个结构体的内存位置,然后我创建结构体,然后使用bar += 1增加地址,并继续创建指针,但我可能错过了一些非常重要的东西。
我真的很感激你的帮助。
CandyBar
的空间。 - jrokvector
或sharedptr
听起来像是可行的选择。 - Lews Therinstd::vector<CandyBar>
。 - fredoverflow(*bars).
和bars->
之间交替使用?看起来很奇怪。另外,当你修改了保存其地址的指针后,如何删除数组? - Mr Lister