Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have anonymous, ad-hoc arrays in C?

Tags:

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; } 
like image 935
rafiki_rafi Avatar asked Feb 03 '13 04:02

rafiki_rafi


People also ask

What is an anonymous array?

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.

What is the meaning of anonymous array in C?

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.


1 Answers

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 
like image 139
Jonathan Leffler Avatar answered Oct 21 '22 02:10

Jonathan Leffler