Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array to function with dynamic declaration of array in C/C++

I want to pass array to function in C/C++ without declaring and assigning it previously. As in C# we can:

fun(new int[] {1, 1}); //this is a function call for void fun(int[]) type function

I am not very sure about the correctness of the above code. But I had done something like this in C#.

How can we pass array to function using dynamic declaration (on the spot declaration)??

I'd tried it using following way. But no luck

fun(int {1,1});
fun(int[] {1,1});
fun((int[]) {1,1});

can't we do so..??

like image 481
shashwat Avatar asked Feb 02 '26 12:02

shashwat


1 Answers

In C99 and later, this:

foo((int[]){2,4,6,8});

is approximately the same as this:

int x[] = {2,4,6,8};
foo(x);

Prior to C99, this is not possible. C++ does not support this syntax either.

like image 157
Oliver Charlesworth Avatar answered Feb 05 '26 01:02

Oliver Charlesworth