Asterisk value as array index in function parameter?

What is the meaning * a function parameter when it is in an array index in C?

 int function(int a[*]) 
+7
c
source share
2 answers

* Used inside [] only to declare function prototypes. Its valid syntax. This is useful when you omit the parameter name from the prototype, for example below

 int function(int, int [*]); 

It tells the compiler that the second parameter is VLA and depends on the value of the first parameter. In the above example, this is not worth it. Take a look at a more useful example.

 int function(int, int [][*]); 

It is not possible to use VLA as a parameter in a function prototype, having unnamed parameters, without using * inside [] .

6.7.6 Declarators

Syntax

  1 declarator:
         [...]
         direct-declarator [type-qualifier-list static assignment-expression]
         direct-declarator [type-qualifier-list opt *]
         direct-declarator (parameter-type-list)
         direct-declarator (identifier-list opt )
+10
source share

Paragraph 6.7.6.2/1 of the standard indicates that in an array type declaration:

In addition to the optional classifier types and the static keyword, [and] can limit the expression or * .

(highlighted by me). Paragraph 4 of the same section explains:

If the size is * instead of an expression, the array type is an array of indefinite sizes of variable length, which can only be used in declarations or type names with a function prototype area

If your implementation supports VLA, this is what you have. The function is declared to accept an argument, which is (a pointer to the first element) an array of variable length of indefinite length.

However, as @WeatherVane noted in the comments, C2011 makes VLA support optional (whereas it was mandatory in C99). For an implementation that does not support VLA, the code is syntactically incorrect.

You can check VLA support through a preprocessor several:

 #if __STDC__ #if __STDC_VERSION__ == 199901L || ( __STDC_VERSION__ >= 201112L && ! __STDC_NO_VLA__ ) // VLAs are supported (or the implementation is non-conforming) #else // VLAs are not supported // (unless the implementation provides VLAs as an extension, which could, // under some circumstances, make it non-conforming) #endif #else // a C89 or non-conforming implementation; no standard way to check VLA support #endif 
+5
source share

All Articles