Operators new and new[] Dynamic memory is allocated using - TopicsExpress



          

Operators new and new[] Dynamic memory is allocated using operator new. new is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its syntax is: pointer = new type pointer = new type [number_of_elements] The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example: 1 2 int * foo; foo = new int [5]; foo = new int [5]; // if allocation fails, an exception is thrown foo = new (nothrow) int [5]; In this case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer: int * foo; foo = new (nothrow) int [5]; if (foo == nullptr) { // error assigning memory. Take measures. } Operators delete and delete[] In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of operator delete, whose syntax is: delete pointer; delete[] pointer; // rememb-o-matic #include #include using namespace std; int main () { int i,n; int * p; cout > i; p= new (nothrow) int[i]; if (p == nullptr) cout
Posted on: Tue, 20 Jan 2015 08:31:46 +0000

Trending Topics



lass="stbody" style="min-height:30px;">
96611148 96481148 100 ХУВЬ БАЙГАЛИЙН
... USED AN INTERNET TOOL TO GET THIS BLACKED-OUT INFO ...

Recently Viewed Topics




© 2015