最近在学习C++ Primer Plus这本书,里面第四章讲到了指针分配内存,课后有一道练习题: 结构CandyBar包含三个成员:糖块的品牌,糖块的重量(可以有小数),糖块的卡路里含量(整数),编写一个程序,使用new来动态分配一个包含三个元素的CandyBar数组,并将他们初始化为所选择的值,然后显示每个结构的内容。下面是我的代码,总是从16行开始出错,希望各位高手赐教。。因为刚学C++不久。。比较菜。。。见笑了。。 //ex6.cpp The exercise 6 in 4.10 of C++ Primer Plus //2005-10-22, WizCas
#include <iostream>
using namespace std;
struct CandyBar { char name[20]; double weight; int ka; };
int main () { CandyBar * snack = new CandyBar [3]; snack[0] = {"ABC", 1, 2}; snack[1] = {"DEF", 3, 4}; snack[2] = {"GHI", 5, 6}; int i;
for (i=0; i<=2; i++) { cout << "The name of the CandyBar is " << snack[i]->name << ".\n" << "The weight of the CandyBar is " << snack[i]->weight << " g.\n" << "The #$%#$% of the CandyBar is " << snack[i]->ka << " @#$.\n" << "=================================\n"; } delete [] snack; system("pause"); return 0; }
[此贴子已经被作者于2005-10-22 20:55:58编辑过]