(新手请教)如何用new来动态分配结构数组问题

u011187286 2013-06-24 10:32:37
stuct snack
{
char candy_name[20];
double candy_weight;
int calorie;
}candybar[3]=
{
{"chocolate",2.5,350},
{"bar",2.0,300},
{"grist",1.5,250}
}
这样一个结构数组,现在要求是,在不声明candybar数组的前提下,用new来动态分配数组,并初使化。
请高手指点,小弟在此问题上困惑不已。
不能用其它的方法哦,只能用new来动态分配数组。

...全文
109 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
greensroll 2013-07-09
  • 打赏
  • 举报
回复
我也是新手,我的是这样的。 #include <iostream> #include <cstring> struct CandyBar { char name[20]; double weight; int calories; }; int main() { using namespace std; CandyBar * ps = new CandyBar[3]; strcpy(ps[0].name, "chocolate"); ps[0].weight = 1.2; ps[0].calories = 350; strcpy(ps[1].name, "bar"); ps[1].weight = 2.5; ps[1].calories = 250; strcpy(ps[2].name, "grist"); ps[2].weight = 1.8; ps[2].calories = 200; cout << "First candy: " << ps[0].name << endl; cout << "Weight: " << ps[0].weight << endl; cout << "Clories: " << ps[0].calories << endl; cout << "Second candy: " << ps[1].name << endl; cout << "Weight: " << ps[1].weight << endl; cout << "Calories: " << ps[1].calories << endl; cout << "Third candy: " << ps[2].name << endl; cout << "Weight: " << ps[2].weight << endl; cout << "Calories: " << ps[2].calories << endl; delete [] ps; return 0; }
greensroll 2013-07-09
  • 打赏
  • 举报
回复
你解出来了么?
u011187286 2013-06-24
  • 打赏
  • 举报
回复
哎,可能是我的编辑器不行,你们两个说的都通过不了。
rocktyt 2013-06-24
  • 打赏
  • 举报
回复
    snack* candybar = new snack [3]
    {
        {"chocolate",2.5,350},
        {"bar",2.0,300},
        {"grist",1.5,250}
    };
这个语法是标准的,但可能要对标准支持比较好的编译器才能编译通过
zilaishuichina 2013-06-24
  • 打赏
  • 举报
回复
snack *candybar = new snack[3]; strcpy(candybar[0]->candy_name, "chocolate"); candybar[0]->candy_weight = 2.5f; candybar[0]->calorie = 350; //others

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧