Pointer & amp; dynamic memory allocation, C language pointer

Source: Internet
Author: User

Pointer & dynamic memory allocation, C language pointer

Dynamic Memory Allocation Mechanism in C ++

C ++ uses new and delete to allocate and release dynamic memory on the stack.

Note. All pointers should be initialized.

If the dynamic memory to which the Pointer Points is released or does not point to a valid address, set the pointer to nullptr. Otherwise, the memory will leak.

Variable:

Double * pvalue {};

Pvalue = new double;

* Pvalue = 9.0;

Or

Double * pvalue {};

Pvalue = new double {9.0 };

Or merge into one sentence.

Double * pvalue {new double {9.0 }};

Delete pvalue;

Array:

Char * pstr {new char [20]};

Delete [] pstr;

Pstr = nullptr;

Can be initialized by the way: int * data {new int [10] {2, 3, 4 }};

Multi-dimensional array:

Double (* pbeans) [4] {};

Pbeans = new double [3] [4];

Or merge as one step: double (* pbeans) [4] {new double [3] [4]};

Delete [] pbeans;

Pbeans = nullptr;

 

Dynamic Memory Allocation Mechanism in C Language

Malloc:

Double * ptd;

Ptd = (double *) malloc (N * sizeof (double ));

Free (ptd );

Request N double-Type Spaces

 

 Calloc:

Long * newmem;

Newmem = (long *) calloc (N, sizeof (long ));

The first parameter is the number of memory units required, and the second parameter is the size of each unit in bytes. Calloc sets all parts of the block to 0.

 

  Dynamic Memory Allocation in a variable-length array (VLA:

Int n = 5;

Int m = 6;

Int ar [n] [m]; // Variable Length Array

Int (* p1) [6];

Int (* p2) [m]; // Variable Length Array

P1 = (int (*) [6]) malloc (n * 6 * sizeof (int ));

P2 = (int (*) [m]) malloc (n * m * sizeof (int); // Variable Length Array

Note: columns must be specified during array transmission as parameters.

For example, double (int ar [] [6]);

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.