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; }
An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable. Properties of Anonymous Arrays: We can create an array without a name.
Answer: Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions.
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).
#include <stdio.h> static void processArray(int n, int arr[]) { for (int i = 0; i < n; i++) printf(" %d", arr[i]); putchar('\n'); } int main(void) { processArray(4, (int[]){0, 1, 2, 3}); return 0; }
When run, it produces the answer:
0 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With