Search code examples
carraysfunctionimplicit-conversiondefinition

Why are arrays of undefined size only allowed in main()?


The main method argument uses an undefined array argv[]

int main(int argc, char *argv[])
{
 .... Do stuff....
}

Why is it undefined arrays are only allowed in the main() method?


Solution

  • In fact this declaration

    int main(int argc, char *argv[])
    

    is equivalent to

    int main(int argc, char **argv)
    

    It is the host environment that supplies an array of strings and passes the pointer to the first string in the array as an argument for the parameter argv.

    From the C Standard (5.1.2.2.1 Program startup)

    — If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase

    As for the comment

    The argv array has no size, how is this possible?

    then a function parameter declared as an array of type T is adjusted to pointer to T.

    So for example these function declarations

    void f( int a[100] );
    void f( int a[10] );
    void f( int a[] );
    

    declare the same one function and the all declarations are adjusted to the declaration

    void f( int *a );
    

    The same way when an argument of an array type is passed to a function then the array is implicitly converted to pointer to its first element.

    So for example the function above can be called like

    int a[100];
    f( a );
    

    or

    int a[10];
    f( a );
    

    or

    int *a;
    f( a );