C++ new operator to allocate memory

Description

C++ new operator to allocate memory

#include <iostream>
#include <cstring>            //for strlen
using namespace std;
int main()//from  w  w w .j a  v a  2  s. c  om
{
   char* str = "This is a test. This is a test.";
   int len = strlen(str);     //get length of str
   char* ptr;                 //make a pointer to char
   ptr = new char[len+1];     //set aside memory: string + '\0'
   strcpy(ptr, str);          //copy str to new memory area ptr
   cout << "ptr=" << ptr << endl;  //show that ptr is now in str
   delete[] ptr;              //release ptr's memory
   return 0;
}



PreviousNext

Related