探索printf函数。问题:printf中可以写无数个输出参数,那么编译器是如何知道输出几个参数呢?
void myPrintf(char*,...);
main()
{
char *a = "xxxx%d, 1111%c ddddd%d xxx%c aaaaaa%d %c";
myPrintf(a,1,'x',5,'y',7,'z');
}
void myPrintf(char *arr,...)
{
}
其实很简单,编译器从printf字符串中查找%的个数,就可以知道有多少个参数了。
void myPrintf(char*,...);
main()
{
char *a = "xxxx%d, 1111%c ddddd%d xxx%c aaaaaa%d %c";
myPrintf(a,1,'x',5,'y',7,'z');
}
void myPrintf(char *arr,...)
{
int stackIndex = 0;
int stringIndex = 0;
int screenIndex = 0;
while(arr[stringIndex] != 0)
{
if(arr[stringIndex] != '%')
{
if(arr[stringIndex] == 'c')
{
*(char far *)(0xb8000000 + 160*10 + screenIndex) = *(char*)(_BP + 6 + stackIndex);
stackIndex += 2;
stringIndex +=2;
screenIndxe +=2;
}
else(arr[stringIndex] == 'd')
{
*(char far *)(0xb8000000 + 160*10 + screenIndex) = *(int*)(_BP + 6 + stackIndex) + 0x30;
stackIndex += 2;
stringIndex +=2;
screenIndxe +=2;
}
}
else
{
*(char far *)(0xb8000000 + 160*10 + screenIndex) = arr[stringIndex];
screenIndex +=2;
stringIndex +=1;
}
}
}
用C语言实现printf函数。
|