about the two warning of sprintf()


        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  !!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值