gcc: Variable Length
1
1 6.19 Arrays of Variable Length
1 ==============================
1
1 Variable-length automatic arrays are allowed in ISO C99, and as an
1 extension GCC accepts them in C90 mode and in C++. These arrays are
1 declared like any other automatic arrays, but with a length that is not
1 a constant expression. The storage is allocated at the point of
1 declaration and deallocated when the block scope containing the
1 declaration exits. For example:
1
1 FILE *
1 concat_fopen (char *s1, char *s2, char *mode)
1 {
1 char str[strlen (s1) + strlen (s2) + 1];
1 strcpy (str, s1);
1 strcat (str, s2);
1 return fopen (str, mode);
1 }
1
1 Jumping or breaking out of the scope of the array name deallocates the
1 storage. Jumping into the scope is not allowed; you get an error
1 message for it.
1
1 As an extension, GCC accepts variable-length arrays as a member of a
1 structure or a union. For example:
1
1 void
1 foo (int n)
1 {
1 struct S { int x[n]; };
1 }
1
1 You can use the function 'alloca' to get an effect much like
1 variable-length arrays. The function 'alloca' is available in many
1 other C implementations (but not in all). On the other hand,
1 variable-length arrays are more elegant.
1
1 There are other differences between these two methods. Space allocated
1 with 'alloca' exists until the containing _function_ returns. The space
1 for a variable-length array is deallocated as soon as the array name's
1 scope ends, unless you also use 'alloca' in this scope.
1
1 You can also use variable-length arrays as arguments to functions:
1
1 struct entry
1 tester (int len, char data[len][len])
1 {
1 /* ... */
1 }
1
1 The length of an array is computed once when the storage is allocated
1 and is remembered for the scope of the array in case you access it with
1 'sizeof'.
1
1 If you want to pass the array first and the length afterward, you can
1 use a forward declaration in the parameter list--another GNU extension.
1
1 struct entry
1 tester (int len; char data[len][len], int len)
1 {
1 /* ... */
1 }
1
1 The 'int len' before the semicolon is a "parameter forward
1 declaration", and it serves the purpose of making the name 'len' known
1 when the declaration of 'data' is parsed.
1
1 You can write any number of such parameter forward declarations in the
1 parameter list. They can be separated by commas or semicolons, but the
1 last one must end with a semicolon, which is followed by the "real"
1 parameter declarations. Each forward declaration must match a "real"
1 declaration in parameter name and data type. ISO C99 does not support
1 parameter forward declarations.
1