Is there some way to pass an array of ints into a function in C, like this:
func(int[]{1, 2, 3});
or like this?
func({1, 2, 3});
I am aware of the existence of va_list, but it's not quite what I am looking for.
Is there some way to pass an array of ints into a function in C, like this:
func(int[]{1, 2, 3});
or like this?
func({1, 2, 3});
I am aware of the existence of va_list, but it's not quite what I am looking for.
It looks like you're looking for a compound literal (defined in C11 §6.5.2.5 Compound literals; also a feature in C99):
func((int[]){ 1, 2, 33, 491 });
A compound literal looks like a cast followed by a braced initializer for the type specified in the cast. The scope of the compound literal is to the end of the statement block in which it is introduced, so it will be valid for the entire block in which the call to func()
is found. Consequently, it is valid for the whole of the call to func()
. And the compound literal is a modifiable value.
We can validly quibble about the interface to the function not specifying how many values are in the array (so how does func()
know how big the array is), but that is somewhat tangential to the idea of the compound literal notation.
The function itself is a perfectly ordinary function taking an array argument:
extern void func(int arr[]);
void func(int arr[])
{
…
}
Or, of course:
extern void func(int *arr);
void func(int *arr)
{
…
}
And (with the major caveat about how the function knows how big the array is), you could write:
void calling_func(void)
{
func((int[]){ 1, 2, 33, 491 });
int array[] = { 2, 99, 462, -9, -31 };
func(array);
}