围棋少年方百花图片:一步一步写算法(之 可变参数)

来源:百度文库 编辑:中财网 时间:2024/04/29 19:10:34

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】


可变参数是C语言编程的一个特色。在我们一般编程中,函数的参数个数都是确定的,事先定下来的。然而就有那么一部分函数,它的个数是不确定的,长度也不一定,这中间有什么秘密吗?

其实,我们可以回忆一下哪些函数是可变参数的函数?其实也就是sprintf、printf这样的函数而已。那么这些函数有什么规律吗?关键就是在这个字符串上面。我们可以举一个例子看看,

view plaincopy to clipboardprint?

  1. void test()
  2. {
  3. printf("%s, value = %d\n", "hello", 10);
  4. }

test函数里面也就是一个简单的打印函数。那么这个函数有什么特别的地方呢,那就是%s、%d和后面的字符是一一对应的,所以有多少个这样的字符,首参数后面就会剩下多少个参数。那么后面参数的地址怎么获取呢?我们可以回想一下,堆栈一般是怎么压栈处理的,

view plaincopy to clipboardprint?

  1. /*
  2. * stack space:
  3. *
  4. * 参数3 | up
  5. * 参数2 |
  6. * 参数1 v down
  7. */
因为参数是按照从右向左依次压入的,所以后面参数的地址依次根据“%”处理即可。下面我们就可以自己写一个PrintInt打印int数据的函数,首先创建一个框架,

view plaincopy to clipboardprint?

  1. void PrintInt(char* buffer, int data, ...)
  2. {
  3. return;
  4. }
然后验证buffer参数中是否有%d,如果存在这样的一个字符,就需要打印一个整数,

view plaincopy to clipboardprint?

  1. void PrintInt(char* buffer, int data, ...)
  2. {
  3. static char space[1024];
  4. char temp[32];
  5. int* start;
  6. int count;
  7. if(NULL == buffer)
  8. return;
  9. memset(space, 0, 1024);
  10. memset(temp, 0, 32);
  11. start = (int*) &buffer;
  12. count = 0;
  13. while(buffer[count]){
  14. if(!strncmp(&buffer[count], "%d", strlen("%d"))){
  15. start ++;
  16. itoa(*start, temp, 10);
  17. strcat(space, temp);
  18. count += 2;
  19. continue;
  20. }
  21. space[strlen(space)] = buffer[count];
  22. count ++;
  23. }
  24. memset(buffer, 0, strlen(buffer));
  25. memmove(buffer, space, strlen(space));
  26. return;
  27. }
为了验证我们的函数是否正确,可以编写测试函数验证一下,

view plaincopy to clipboardprint?

  1. void display()
  2. {
  3. char buffer[32] = {"%d %d %d %d\n"};
  4. PrintInt(buffer, 1, 2, 3, 4);
  5. printf(buffer);
  6. }