New and delete

Source: Internet
Author: User

New and delete can dynamically create arrays and delete arrays.

Char *a = new Char;

Delete A;

Char *a = new CHAR[12]//Create a 12-byte character array

delete [] A;

int *a = new INT[12]; Create an array of 12 byte-shaped

delete [] A;

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int Main () {    int *a = new INT[10];    for (int i = 0; i < ten; I + +) {        A[i] = i;    }    for (int i = 0; i < ten; I + +) {        cout << a[i] << Endl;    }    delete [] A;    return 0;}

Creating a two-dimensional array

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int Main () {    int **a = new int* [ten];         Note that the previous pointer is higher than the next pointer for    (int i = 1; I <=; i + +) {   //two-D pointers are created as a Villivi.        a[i-1] = new int[i];    }    for (int i = 1; I <=; i + +) {for        (int j = 0; J < i; J + +) {            A[i-1][j] = i;        }    }    for (int i = 1; I <=; i + +) {for        (int j = 0; J < i; J + +) {            cout << a[i-1][j]<< "";        }        cout << Endl;    }    for (int i = 1; I <=; i + +) {//two-D pointer deletion is to delete a one-dimensional pointer before deleting a two-dimensional pointer.        Delete [] a[i-1];    }    delete [] A;    return 0;}


Attention:

Use new in the constructor to initialize the pointer to the object, you should use delete in the destructor.

New and delete must be compatible with each other. The new corresponds to delete,new [] corresponding to delete [].

If you have more than one constructor, you must use new in the same way, either with brackets or without. Because there is only one destructor, all constructors must be compatible with it. However, you can use new in one constructor to initialize the pointer, and the pointer is initialized to NULL in another constructor, because the delete can be used with a null pointer.


New and delete

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.