carraysfunctionon-the-fly

Is it possible to pass an "on the fly" array to a C function?


In Fortran, one can pass an array constructed on the fly to a subroutine:

call sub_that_wants_3_elm_array((/1,2,3/),output_arg)

Is it possible to do something analogous in C? This seems awfully basic, but I haven't been able to find anything on this, either yes or no.


Solution

  • Yes. It's possible using compound literals (since C99).

    E.g.

    #include <stdio.h>
    
    void fun(int *a)
    {
        printf("%d\n", a[2]); //prints 72
    }
    
    int main(void)
    {
        fun((int[]){1, 99, 72});
    }
    

    You can find some more examples from the links as well:

    1. The New C: Compound Literals
    2. Compound Literals - gcc