动态数组结构
CandyBar *snack=new CandyBar[3];为指针snack分配了空间后,为什么我不能用snack[0]->name;snack[1]->name;snack[2]->name;
程序代码:
#include<iostream> #include<cstring> #include<string> using namespace std; struct CandyBar{ string name; double kg; int cal; }; int main() { CandyBar *snack=new CandyBar[3]{ {"Mocha Munch",2.3,350}, {"Mocha Munch",2.3,351}, {"Mocha Munch",2.3,352}}; cout<<snack->name<<endl<<snack->kg<<endl<<snack->cal<<endl; cout<<(snack+1)->name<<endl<<(snack+1)->kg<<endl<<(snack+1)->cal<<endl; cout<<(snack+2)->name<<endl<<(snack+2)->kg<<endl<<(snack+2)->cal<<endl; }