C + +--dynamic array

Source: Internet
Author: User


first, about the use of arrays , there are several special places to note:

1. One-dimensional array name can be used as a pointer

Application: A one-dimensional array/two-dimensional array of arguments (see blog "C + +--two-D array parameter passing Http://www.cnblogs.com/cygalaxy/p/6963789.html")

2. Dynamic arrays

specific application: According to the actual need for an array to open the specific size.

int*p;//declares the dynamic array p as a global variable, and determines the actual length within the functionintMain () {intA=5; P=New int(A *sizeof(int));//Open 5 int element space for dynamic array P     for(intI=0;i<5;++i) {P[i]=i*2; P[i] equivalent to * (p+i) cout<<p[i]<<" "; } cout<<Endl; return 0;}

Operation Result:

0 2 4) 6 8

Two, several dynamic array Introduction:

1. Using STL Vector<t>, convenient, no need to consider open space

2. Using the pointer, as shown above, first declare a pointer, and then use new (in C language with malloc) to request the actual memory.

3.c++primer5 in the section describing arrays explicitly states that declaring an array cannot use a variable, as detailed below:

 int  a=5   int  arr[a]={0 , 1 , 2 , 3     , 4 }; //  error, A is not a constant  const  int  b= ; int  arr1[b]={0 , 1 , 2 , 3  , 4 }; //  correct, B is constant  

But some compilers can do this, and it could be a compiler extension!

C + +--dynamic array

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.