when I write code in my project, there is an int type argument just can not cast to string, so I write anther small program to test the sprintf() as follow,(the itoa() is copy from other place to compare it result ), it's really shit when I find the problem
/* sprint.c write by vinco at 2011-07-29
*
*/
#include<stdio.h>
#include<string.h>
const char * itoa(int i);
int main()
{
char var[32];
int i=100;
char* p=NULL;
#if 0
sprintf(var,"%s",i);
printf("var=%s\n",var);
#else
p = itoa(i);
printf("itoa(%d)=%s\n",i,p);
#endif
return 0;
}
const char * itoa(int i)
{
static char buf[256];
sprintf(buf,"%d",i);
return buf;
}
1. #if 0
now call itoa(), waring as following , even so, it can be executed correctly :
root@vinco:/home/vinco# gcc sprint.c -o sprint
sprint.c: In function ‘main’:
sprint.c:22: warning: assignment discards qualifiers from pointer target type
root@vinco:/home/vinco# ./sprint
itoa(100)=100
root@vinco:/home/vinco#
2. #if 1
now call "sprintf(var,"%s",i);" waring as following , it cann't be executed normaly:
root@vinco:/home/vinco# gcc sprint.c -o sprint
sprint.c: In function ‘main’:
sprint.c:17: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
root@vinco:/home/vinco# ./sprint
Segmentation fault
root@vinco:/home/vinco#
3. analyzed as follow:
in case #if 0:
sprint.c:22: warning: assignment discards qualifiers from pointer target type
means itoa() return type "const char * " ,it's assigned to a variable whose type is "char * ",it 's warning without doubt when compile it . to avoid it ,you can modify it as following:
const char* p=NULL;
in case #if 1:
it's reall incomprehensible to some extent if you change the value of variable i to zero(line 12):
int i=0;
compile and execute it , it seem that the "error" doesn't that much:
root@vinco:/home/vinco# gcc sprint.c -o sprint
sprint.c: In function ‘main’:
sprint.c:17: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
root@vinco:/home/vinco# ./sprint
var=(null)
root@vinco:/home/vinco#
it can be executed ,but only get "var=(null)" !!!
---------------------------------------------------------------------------------------------
int sprintf ( char * str, const char * format, ... );
---------------------------------------------------------------------------------------------
after half an hour, I abruptly realize that the "format " must be unifrom with the types of argment list ,after modified line 17:
sprintf(var,"%d",i);
it 's perfect !!!