Is it possible to create anonymous, ad-hoc arrays in C?
For example, suppose I have a function called processArray(int[] array) that takes an int array as its argument, can I pass it an anonymous array in the following way:
int main(){
processArray( (int[]){0, 1, 2, 3} ); //can I create this type of array?
return 0;
}
Or do I have to declare the array previously (with a pointer), and then pass its pointer to processArray()? For example:
int main(){
int[] myArray = {0, 1, 2, 3};
processArray(myArray);
return 0;
}
With C99 and C11, you can write what you wrote, as exemplified by the following code. These are ‘compound literals’, described in ISO/IEC 9899:2011 §6.5.2.5 Compound literals (and it is the same section in ISO/IEC 9899:1999).
When run, it produces the answer: