Passing array to function with dynamic declaration

2019-06-01 01:35发布

问题:

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..??

回答1:

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.



回答2:

In C++11, you can use an initializer list:

#include <initializer_list>
#include <iostream>

void fun(std::initializer_list<int> numbers)
{
    for (int x : numbers)
        std::cout << x << ' ';
    std::cout << '\n';
}

int main()
{
    fun( {2, 3, 5, 7, 11, 13, 17, 19} );
}


回答3:

This is possible in ANSI C99 and C11, but not in C89.



回答4:

May I suggest using a variable argument list?

The declaration syntax would be as follows:

void Function(int Count, ...) {
     va_list va;
     va_start(va, Count);
     for(int i = 0; i < Count; ++i) {
         int nextVar = va_arg(va, int);
         //Do some stuff with the array element
     }
     va_end(va);
}

This function is called with:

Function(4, 2, 3, 1, 5);

2, 3, 1 and 5 are the 'array elements'.

Alternatively, if you 'need' an array to go through within that function, it's easy to move the variable list to a proper (dynamic) array, by using new and delete.

Within the va-function:

 int *Array = new int[Count];
 for(int i = 0; i < Count; ++i) {
      Array[i] = va_arg(va, int);
 }
 //Do Stuff with Array
 delete[] Array;