C++ static initialization array and dynamic initialization array details

  • 2020-06-07 04:56:54
  • OfStack

The length of the statically initialized array must be a constant determined in the program, not a variable entered by the user

Example:


int a[10];// correct 

Student stud[10];// Correct: Student is 1 A student class 

int n;cin>>n;int a[n];// error 

int n;cin>>n;Student stud[n];// Error: Student is 1 A student class 

Dynamically initializing arrays can use user-entered variables as the length of the array.

Example:


int n;

cin>>n;

int *a=new int[n];// The length of the integer array does not need to be determined in the program and can be entered by the user while the program is running 

int n; 

cin>>n; 

cin>>n; 

Student *stud=new Student[n]; // So that the length of the student array doesn't have to be determined in the program,   Can be entered by the user while the program is running 

Note: Static initializers allocate space at definition time and call constructors with or without parameters

Here's the problem: if I want to use static initialization arrays, but my input length depends on cin > > n; What do you do?

If we don't use dynamic initialization arrays, using static initialization arrays, the length of the array need to be determined by the program runs, can be in the program initialization a larger array, only used when running the program is partial n array length, although it will waste of memory resources, but also is one kind of solution!!!!!

Example:


int a[200];

int n;

cin>>n; // I'm just using the front of the array n An offset 

for(int k=0; k<n; k++)

cin>>a[k];

Student stud[200];

int n;

cin>>n;// I'm just using the front of the array n An offset 

for(int k=0;k<n;k++)

cin>>stud[k];

Note: Dynamic initializers do not allocate space when defining Pointers, and the new statement only calls the constructor to allocate space and initialize it

The similarities and differences with C/C++ static initialization arrays need to be highlighted by one point :(this is not an analysis and was discovered during the vs2015 runtime)

In C, int n=1; int a [n]; / / error

In C, int const n=1; int a [n]; / / error

In C++ language: int n=1; int a [n]; / / error

In C++ language: int const n=1; int a [n]; / / right


Related articles: