lifuguan 2016-04-28 08:27 采纳率: 26.7%
浏览 1654
已采纳

C++中delete操作符问题(为什么没有new也用delete)

为什么没有new也用delete

 // Soln5_5.cpp
#include <iostream>
#include <cstring>

char* parse(const char* str)
{
  static char* pStr{};
  static size_t len{};
  static size_t start{};
  size_t pos{};
  char* pReturn{};

  // First time through, save the string
  if (str)
  {
     delete pStr;                              // in case it was allocated
     len = strlen(str);
     pStr = new char[len+1];
     strcpy_s(pStr, len+1, str);
  }

  if (start >= len)
     return nullptr;

  // Walk the string from 'start' till we find a blank or the end
  for (pos = start; pStr[pos] != ' ' && pStr[pos] != '\0'; ++pos);

  // Copy the string if we've a word to return, otherwise return NULL
  if (pos != start)
  {
    pReturn = new char[pos - start + 2];
    size_t i{};
    for (size_t j{ start }; j < pos; ++i, ++j)
      pReturn[i] = pStr[j];
      pReturn[i] = '\0';
      start = pos + 1;
      return pReturn;
   }
   else
     return nullptr;
}

int main()
{
  char s1[] {"seventy-one fruit balls, please Doris"};
  std::cout << "string is '" << s1 << "'\n\nParsing...\n";
  char* p{ parse(s1) };

   while (p)
   {
     std::cout << p << std::endl;
      delete[] p;//为什么没有new也用delete
      p = parse(nullptr);
   }
}

  • 写回答

2条回答

  • lambda-fk 2016-04-29 02:46
    关注

    要相信科学

    delete只能删除你自己new 出来的那个地址

    pReturn = new char[pos - start + 2];

    这个返回的地址是你new出来的哦

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝