I am wondering how does printf() figure out when to stop printing a string, even I haven\'t put a termination character at the end of the string? I did an experiment by mall
Well, well well, keep aside the whole MALLOC thing cause for PRINTF its all just a string right, i know the %d, %x, %s and all we use as format specifiers but the thing is printf if a mere "C" function which can intake variable number of arguments.
In simpler words printf is a special function which treats the string as a variable number of CHAR type arguments passed to it.
Any argument of \n,\t etc or %c,%f etc is a single character for it and is worked upon as special case.
void myprintf(char * frmt,...)
{
char *p;
int i;
unsigned u;
char *s;
va_list argp;
va_start(argp, fmt);
p=fmt;
for(p=fmt; *p!='\0';p++)
{
if(*p=='%')
{
putchar(*p);continue;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0){i=-i;putchar('-');}puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,argp, unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
char *convert(unsigned int, int)
{
static char buf[33];
char *ptr;
ptr=&buf[sizeof(buff)-1];
*ptr='\0';
do
{
*--ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
Hope this helps, if it doesn't just let me know, I'd be glad to be of any help to you :)