鱼C论坛

 找回密码
 立即注册
查看: 1814|回复: 5

[已解决]C++ Primer Plus 第8章 编程题4

[复制链接]
发表于 2020-1-13 22:35:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
C++ Primer Plus Chpater8 Program4.png

这段程序要求在set函数中使用new来申请空间,因此我又写了一段unset,用来释放内存。程序会出错,怎么才能在一个函数里面申请空间,在另一个函数释放内存呢?

  1. #include <iostream>
  2. #include <cstring>

  3. using namespace std;

  4. struct stringy {
  5.         char * str;
  6.         int ct;
  7. };

  8. void set(stringy &dst, char *src);
  9. void unset(stringy &src);
  10. void show(const stringy &src, int n = 1);

  11. int main()
  12. {
  13.         stringy beany;
  14.         char testing[] = "apple";

  15.         set(beany, testing);
  16.         show(beany);
  17.         show(beany, 2);
  18.         unset(beany);


  19.         return 0;
  20. }

  21. void set(stringy &dst, char *src)
  22. {
  23.         int n = strlen(src);
  24.         dst.str = new char[n];
  25.         strcpy(dst.str, src);
  26.         dst.ct = n;
  27. }

  28. void unset(stringy &src)
  29. {
  30.         delete[] src.str;
  31. }

  32. void show(const stringy &src, int n)
  33. {
  34.         cout << src.ct << endl;
  35.         for (int i = 0; i < n; i++) {
  36.                 cout << src.str << endl;
  37.         }
  38. }
复制代码
最佳答案
2020-1-13 22:58:36
本帖最后由 superbe 于 2020-1-13 23:00 编辑

void set(stringy &dst, char *src)
{
    int n = strlen(src);
    dst.str = new char[n+1];   // [n] 改成 [n+1],加 1 是保存结束符 ‘\0’ 的
    strcpy(dst.str, src);
    dst.ct = n;
}
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-1-13 22:58:36 | 显示全部楼层    本楼为最佳答案   
本帖最后由 superbe 于 2020-1-13 23:00 编辑

void set(stringy &dst, char *src)
{
    int n = strlen(src);
    dst.str = new char[n+1];   // [n] 改成 [n+1],加 1 是保存结束符 ‘\0’ 的
    strcpy(dst.str, src);
    dst.ct = n;
}
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-1-13 23:08:33 | 显示全部楼层
superbe 发表于 2020-1-13 22:58
void set(stringy &dst, char *src)
{
    int n = strlen(src);

请问,是不是因为delete的时候要通过'\0'来判断 delete多少个?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-1-13 23:11:53 | 显示全部楼层
跟怎么删除没关系,
  1. void set(stringy &dst, char *src)
  2. {
  3.         int n = strlen(src);
  4.         dst.str = new char[n];  //这里溢出了,str的长度应该设为n+1
  5.         strcpy(dst.str, src);
  6.         dst.ct = n;
  7. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-1-13 23:21:29 | 显示全部楼层
Croper 发表于 2020-1-13 23:11
跟怎么删除没关系,

多谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-1-13 23:33:18 | 显示全部楼层
strlen()得到的长度没有包括末尾的\0,而strcpy()拷贝字符串时连同\0也拷贝在内,所以分配的内存应该是strlen()+1。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-7 13:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表