Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c - How to pass a array's total elements as an function's postion parameter?

I had a array in c:

int array[] = {1, 2, 3, 4};

and I had a function's protype like this:

int add_all(int a, int b, int c, int d);

But how can I pass the array's all elements as the function's parameter at one time?

I know in python, this can be done like this:

array=[1,2,3,4]
add_all(*array)

Could someone tell me how to achieve the same effect in C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/control/while.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/push_back.hpp>
#include <boost/preprocessor/tuple/reverse.hpp>

#define ARRAY_ELEM(x,n) x[n]

#define PRED(n, state) BOOST_PP_TUPLE_ELEM(3, 1, state)

#define OP(d, state) 
   OP_D( 
      d, 
      BOOST_PP_TUPLE_ELEM(3, 0, state), 
      BOOST_PP_TUPLE_ELEM(3, 1, state), 
      BOOST_PP_TUPLE_ELEM(3, 2, state) 
   ) 

#define OP_D(d, res, c, arr_name) 
   ( 
      BOOST_PP_TUPLE_PUSH_BACK(res,ARRAY_ELEM(arr_name,BOOST_PP_DEC(c))), 
      BOOST_PP_DEC(c), 
      arr_name 
   ) 


#define UNPACK_REVERSE(ARR_NAME,N) 
    BOOST_PP_TUPLE_ELEM( 
      3, 0, 
      BOOST_PP_WHILE(PRED, OP, ((ARRAY_ELEM(ARR_NAME,BOOST_PP_DEC(N))), 
                    BOOST_PP_DEC(N),ARR_NAME) ) 
   )
/*The macro to be called*/
#define UNPACK(ARR_NAME,N) 
    BOOST_PP_TUPLE_REVERSE(UNPACK_REVERSE(ARR_NAME,N))

And here's a usage example:

void print3(int x, int y, int z){
    printf("%d,%d,%d
",x,y,z);
}
int main(){
    int z[3]={1,2,3};
    print3 UNPACK(z,3);
    return 0;
}

This macro uses Boost's Preprocessor library in a loop to generate and expand the array elements in a tuple. Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...