Variable-length array in C Language
We know that the traditional C language does not support variable-length arrays as C ++ does. That is to say, the length of arrays is determined during compilation and cannot be changed during runtime. The new features of C language are defined in the c99 standard. A new feature allows you to use variable-length arrays in C.
C99 gives C programmers the ability to use variable length arrays, which are arrays whose sizes are not known until run time. A Variable Length array declaration is like a fixed array declaration limit t that the array size is specified by a non-constant expression. when the Declaration is encountered, the size expression is evaluated and the array is created with the indicated length, which must be a positive integer. once created, variable length array cannot change in length. elements in the array can be accessed up to the allocated length; accessing elements beyond that length results in undefined behavior. there is no check required for such out-of-range accesses. the array is destroyed when the block containing the Declaration completes. each time the block is started, a new array is allocated.
The above is the c99 standard description of the C language variable-length array.
C Variable Length array, the source code used for testing is very simple, as shown below:
- // File name: dynarray. c
- // Compilation environment: bloodshed Dev-C/C ++ 4.9
- # Include <stdio. h>
- # Define bzero (B, Len) (memset (B), '/0', (LEN), (void) 0)
- Int main (INT argc, char * argv [])
- {
- Int I, N;
- N = atoi (argv [1]);
- Char arr [n + 1];
- Bzero (ARR, (n + 1) * sizeof (char ));
- For (I = 0; I <n; I ++ ){
- Arr [I] = (char) ('A' + I );
- }
- Arr [N] = '/0 ';
- Printf ("% s/n", arr );
- Getchar ();
- Return (0 );
- }
The above program is named dynarray. C. The job is to add 1 to the value n of argv [1] As the length of ARR, And the ARR type of the variable-length array is Char. Then write some characters into the array and output the written strings.
After compiling on the c 99 standard IDE, run:
C:/c99_test/dynarray.exe 6
Output:
Abcdef