资源描述:
《C编程的可变参数》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、可变参数是C语言编程的一个特色。在我们一般编程中,函数的参数个数都是确定的,事先定下来的。然而就有那么一部分函数,它的个数是不确定的,长度也不一定,这中间有什么秘密吗? 其实,我们可以回忆一下哪些函数是可变参数的函数?其实也就是sprintf、printf这样的函数而已。那么这些函数有什么规律吗?关键就是在这个字符串上面。我们可以举一个例子看看, voidtest() { printf("%s,value=%d","hello",10); } voidtest(){ printf("%s,value=%d"
2、,"hello",10);} test函数里面也就是一个简单的打印函数。那么这个函数有什么特别的地方呢,那就是%s、%d和后面的字符是一一对应的,所以有多少个这样的字符,首参数后面就会剩下多少个参数。那么后面参数的地址怎么获取呢?我们可以回想一下,堆栈一般是怎么压栈处理的, /**stackspace:** 参数3
3、 up* 参数2
4、* 参数1 v down*/ /**stackspace:** 参数3
5、 up* 参数2
6、* 参数1
7、 v down*/ 因为参数是按照从右向左依次压入的,所以后面参数的地址依次根据“%”处理即可。下面我们就可以自己写一个PrintInt打印int数据的函数,首先创建一个框架, voidPrintInt(char*buffer,intdata,...) { return; } voidPrintInt(char*buffer,intdata,...){ return;} 然后验证buffer参数中是否有%d,如果存在这样的一个字符,就需要打印一个整数, voidPrintInt(char*buffer,i
8、ntdata,...) { staticcharspace[1024]; chartemp[32]; int*start; intcount; if(NULL==buffer) return; memset(space,0,1024); memset(temp,0,32); start=(int*)&buffer; count=0; while(buffer[count]){ if(!strncmp(&buffer[count],"%d"
9、,strlen("%d"))){ start++; itoa(*start,temp,10); strcat(space,temp); count+=2; continue; } space[strlen(space)]=buffer[count]; count++; } memset(buffer,0,strlen(buffer)); memmove(buffer,
10、space,strlen(space)); return; } voidPrintInt(char*buffer,intdata,...){ staticcharspace[1024]; chartemp[32]; int*start; intcount; if(NULL==buffer) return; memset(space,0,1024); memset(temp,0,32); start=(int*)&bu
11、ffer; count=0; while(buffer[count]){ if(!strncmp(&buffer[count],"%d",strlen("%d"))){ start++; itoa(*start,temp,10); strcat(space,temp); count+=2; continue
12、; } space[strlen(space)]=buffer[count]; count++; }