New assignment of dynamic arrays in C + +

Source: Internet
Author: User

Variable-length one-dimensional arrays
The variable-length array here refers to an array that cannot determine the length of the array at compile time, and the program needs to dynamically allocate memory space at run time. The simplest way to implement a variable-length array is to change the length of a one-dimensional array, which you can do:

File name:   array01.cpp  #include <iostream>  using   namespace   std;  int   Main ()  {  int   len;  cin>>len;  Use pointer p to point to new dynamically allocated memory space of len*sizeof (int)   *p=new   Int[len];  ...........  Delete[]   p;  return   0;  }  

Note int *p=new Int[len];

This sentence, you cannot do this:
int P[len];
The C + + compiler will complain that Len's size cannot be determined, because the array is declared in this form, and the size of the array needs to be determined at compile time. And that's not true:
int p[]=new Int[len];
The compiler will say the int* type can not be converted to int[] type, because a memory space opened with new will return the first address of the memory, so to assign this address to a pointer, so to use an int *p=new Int[len];
Array01.cpp implements a variable-length one-dimensional array, but to develop a good habit is to note that you want to unregister the pointer p so that the program frees up the memory space opened with new.

New assignment of dynamic arrays in C + +

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.