2 visual studio1 VISUAL_STUDIO1 于 2016.04.28 16:27 提问

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);
   }
}

3个回答

fk002008
fk002008   2016.04.29 10:46
已采纳

要相信科学

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

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

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

oyljerry
oyljerry   Ds   Rxr 2016.04.28 22:01

parse内部中有new

CSDNXIAOD
CSDNXIAOD   2016.04.28 16:32

C++中的new和delete操作符
C++ new和delete操作符
C++ new和delete操作符
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!