C++ Primer Plus第六版编程练习8.2解答

#include <iostream>
#include <cstring>

struct CandyBar
{
    char *brand;
    double weight;
    int calories;
};

void set(CandyBar & cb,char *brand="Millennium Munch",double wegiht=2.85,int calories=350);//设置默认参数
void show(const CandyBar & cb);

using std::cout;
using std::cin;
using std::endl;

int main()
{
    CandyBar candybar;
    set(candybar);
    show(candybar);
    delete [] candybar.brand;  //由于再次使用时会对candybar.brand指针重新赋值,所以在此前要先释放该内存

    set(candybar,"Mario",3.98,300);
    show(candybar);
    delete [] candybar.brand;  //同理,使用完后要释放candybar.brand指向的动态存储空间

    return 0;
}

void show(const CandyBar & cb)
{
    cout<<"brand: "<<cb.brand<<endl;
    cout<<"weight: "<<cb.weight<<endl;
    cout<<"calories: "<<cb.calories<<endl;
    cout<<endl;
}

void set(CandyBar & cb,char *name,double weight,int calories)
{
    cb.brand=new char[strlen(name)+1];
    //注意这里不能直接让cb.brand=name,因为cb.brand是一个还没有确定存储位置的空指针,
    //直接对其赋值是危险的,编译不会报错,但运行时会出错
    //而使用new后则是开辟了一段动态存储空间并让cb.brand指向它,
    //此时cb.brand的存储位置才是确定的,才能对它赋值

    cb.brand=name;  //此时才可以对cb.name指针赋值
    cb.weight=weight;
    cb.calories=calories;
}

 


本题的关键在于对char指针的处理

大家可以看看另一篇我转的文章:char *p 与char p[] 比较一些总结


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值