lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

c: 可变参数

 

 

 

 

一、可变参数源码

 

 1 [root@rocky c]# cat  arg_test.c 
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<stdarg.h>
 5 #include<string.h>
 6 
 7 
 8 
 9 
10 void ucat(int size, char *str, ...)
11 {
12         char buff[1024];
13         char *tmp;
14 
15         strcat(buff, str);
16         strcat(buff, "->");
17 
18         va_list vl;
19         va_start(vl, str);
20         for(int i=0; i<size; i++)
21         {
22                 tmp = va_arg(vl, char*);
23                 printf("tmp_%d = %s\n", i, tmp);
24                 strcat(buff, tmp);
25                 // set the number of string "->"
26                 if( i < (size - 1) ){
27                         strcat(buff, "->");
28                 }
29         }
30         va_end(vl);
31 
32         printf("result: %s\n", buff);
33 
34 }
35 
36 
37 
38 
39 int main(int argc, char *argv[], char *envp[])
40 {
41 
42         ucat(6,"string", "string0", "string1","string2","string3","string4","string5" );
43 
44 
45         return 0;
46 
47 }

 

 

 

 

二、运行结果

 

 1 [root@rocky c]# cat  arg_test.c 
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<stdarg.h>
 5 #include<string.h>
 6 
 7 
 8 
 9 
10 void ucat(int size, char *str, ...)
11 {
12         char buff[1024];
13         char *tmp;
14 
15         strcat(buff, str);
16         strcat(buff, "->");
17 
18         va_list vl;
19         va_start(vl, str);
20         for(int i=0; i<size; i++)
21         {
22                 tmp = va_arg(vl, char*);
23                 printf("tmp_%d = %s\n", i, tmp);
24                 strcat(buff, tmp);
25                 // set the number of string "->"
26                 if( i < (size - 1) ){
27                         strcat(buff, "->");
28                 }
29         }
30         va_end(vl);
31 
32         printf("result: %s\n", buff);
33 
34 }
35 
36 
37 
38 
39 int main(int argc, char *argv[], char *envp[])
40 {
41 
42         ucat(6,"string", "string0", "string1","string2","string3","string4","string5" );
43 
44 
45         return 0;
46 
47 }
48 [root@rocky c]# 
49 [root@rocky c]# 
50 [root@rocky c]# ./arg_test 
51 tmp_0 = string0
52 tmp_1 = string1
53 tmp_2 = string2
54 tmp_3 = string3
55 tmp_4 = string4
56 tmp_5 = string5
57 result: string->string0->string1->string2->string3->string4->string5
58 [root@rocky c]# 
59 [root@rocky c]# 

 

posted on 2022-12-28 03:10  lnlidawei  阅读(85)  评论(0编辑  收藏  举报