专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

puts()无法打印空指针,而printf()可以?该怎么处理

发布时间:2011-06-28 14:48:58 文章来源:www.iduyao.cn 采编人员:星星草
puts()无法打印空指针,而printf()可以?
下面这样一个程序,如果函数返回为NULL的话,用put打印:编译报错,提示:"Debug Assertion Failed!";而printf()去可打印出"(null)" 的字符样,这是什么原因?(请大家指点!)

#include<stdio.h>

#define N 80

char *str_chr(char * ,char);
int main()
{
char str[N];

while (gets(str) != NULL) 

printf("%s\n",str_chr(str,'c')); // 它与puts(str_chr(str,'c'));的区别
}
char *str_chr(char *str,char c)
{
while (*str && *str != c)
str++;

if (*str == '\0')
return NULL;
else 
return str;
}

------解决方案--------------------
printf和puts在打印之前最好都要进行指针的判空处理,尤其是用%s打印的时候,printf在打印空指针的时候,编译器估计做了处理。。。
------解决方案--------------------
最好不要依赖这种行为
对于可能的NULL要进行判断
------解决方案--------------------
应该是puts()函数里参数不能为空。
------解决方案--------------------
C/C++ code

/***
*int puts(string) - put a string to stdout with newline
*
*Purpose:
*       Write a string to stdout; don't include '\0' but append '\n'.  Uses
*       temporary buffering for efficiency on stdout if unbuffered.
*
*Entry:
*       char *string - string to output
*
*Exit:
*       Good return = 0
*       Error return = EOF
*
*Exceptions:
*
*******************************************************************************/

int __cdecl _putts (
        const _TCHAR *string
        )
{
        int buffing;
#ifndef _UNICODE
        size_t length;
        size_t ndone;
#endif  /* _UNICODE */
        int retval = _TEOF; /* error */

        _VALIDATE_RETURN( (string != NULL), EINVAL, _TEOF );
#ifndef _UNICODE
        _VALIDATE_STREAM_ANSI_RETURN(stdout, EINVAL, EOF);
#endif  /* _UNICODE */

        _lock_str2(1, stdout);
        __try {

        buffing = _stbuf(stdout);

#ifdef _UNICODE
        while (*string) {
            if (_putwchar_nolock(*string++) == WEOF)
                goto done;
        }
        if (_putwchar_nolock(L'\n') != WEOF)
            retval = 0;     /* success */
#else  /* _UNICODE */
        length = strlen(string);
        ndone = _fwrite_nolock(string,1,length,stdout);

        if (ndone == length) {
            _putc_nolock('\n',stdout);
            retval = 0;     /* success */
        }
#endif  /* _UNICODE */

#ifdef _UNICODE
done:
#endif  /* _UNICODE */
        _ftbuf(buffing, stdout);

        }
        __finally {
            _unlock_str2(1, stdout);
        }

        return retval;
}

------解决方案--------------------
在puts里面有下面这样的判定:

_VALIDATE_RETURN( (string != NULL), EINVAL, _TEOF );

在puts(str_chr(str,'c'));之前,可以先判断一下str_chr(str,'c')的返回值是否为NULL,如果是NULL,就puts("NULL");或者直接return。
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: