Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of asterisk as index of array in function parameter? [duplicate]

Tags:

c

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

int function(int a[*])
like image 551
Sabrina Avatar asked Feb 22 '17 16:02

Sabrina


2 Answers

* is used inside [] only to declare function prototypes. Its a valid syntax. It's useful when you omit parameters name from the prototype like example below

int function(int, int [*]);

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

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

This can't be 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-listopt * ]
        direct-declarator ( parameter-type-list )
        direct-declarator ( identifier-listopt )
like image 178
haccks Avatar answered Oct 18 '22 00:10

haccks


Paragraph 6.7.6.2/1 of the standard specifies that in an array-like declaration:

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *.

(emphasis added). Paragraph 4 of the same section explains:

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

Provided that your implementation supports VLAs, that's what you have. The function is declared to accept an argument that is a (pointer to the first element of) a variable-length array of unspecified length.

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

You can check for VLA support via the preprocessor, somewhat:

#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
like image 41
John Bollinger Avatar answered Oct 17 '22 23:10

John Bollinger