I have following question on function with Variable length argument in C:
Case 1 (Works)
myPrintf("%d %s", 24, "Hi There");
Case 2 (Works)
char tempbuf[9]="Hi There";`
myPrintf("%s %d", tempbuf, 24)
Case 3 (Doesn't work)
myPrintf("%s %d", "Hi There", 24)
Does anyone has any idea why the case 3 doesn't work. I could see str = va_arg(ap, char *); returning 24 for this case intead of the actual string.
Code for myPrintf: (It is not fully functional though)
void myPrintf(char *fmt, ...)
{
int i,j,val,len;
char *str;
int len2;
va_list ap;
char tempBuf[128];
len=strlen(fmt);
memset(tempBuf,0,MAX_MSZ_LEN);
va_start(ap,fmt);
for(i=0; i<len; i++)
{
switch(fmt[i])
{
case '%' :
i++;
if( fmt[i] == 's' )
{
str = va_arg(ap, char *);
strcat(tempBuf, str);
}
else
if( fmt[i]=='i' || fmt[i]=='d' )
{
val=va_arg(ap,int);
sprintf(str,"%d",val);
strcat(tempBuf, str);
}
default :
len2=strlen(tempBuf);
tempBuf[len2]=fmt[i];
}
}
va_end(ap);
}
}
myPrintf()?myPrintfto offer much help - it looks like a sensible code fragment so far.myPrintfandmyprintffor that matter?