空终止字符串 [英] null terminating a string

查看:127
本文介绍了空终止字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.4.4 C89

什么是空终止字符串的标准方式?当我使用 NULL 我得到一个警告消息。

  * DEST ++ = 0;
* DEST ++ ='\\ 0';
* DEST ++ = NULL; / *警告:分配需要从指针整数,未作投* /

来源$ C ​​$ C:

 为size_t s_strscpy(字符* DEST,为const char * SRC,常量size_t型LEN)
{
    / *从SRC将内容复制到DEST * /
    为size_t I = 0;
    对于(i = 0; I< LEN,我++)
    * DEST ++ = * SRC ++;    / *空终止DEST * /
     * DEST ++ = 0;    返回我;
}

另一个问题:我故意注释掉空终止该行。但是,它仍然正确打印出dest的内容。这个函数的调用者将派遣由任一字符串的长度包括 NULL 与否。即的strlen(SRC)+ 1 stlen(SRC)

 为size_t s_strscpy(字符* DEST,为const char * SRC,常量size_t型LEN)
{
    / *从SRC将内容复制到DEST * /
    为size_t I = 0;
    / *不要复制空终止* /
    对于(i = 0; I< LEN - 1;我++)
    * DEST ++ = * SRC ++;    / *不添加空终止符* /
    / * * DEST ++ = 0; * /    返回我;
}


解决方案

要你的第一个问题:
我会去与保罗的r评论和终止'\\ 0'。但值 0 本身的作品也很好。口味的问题。但是,不要使用宏 NULL 这是为指针。

要你的第二个问题:
如果字符串不与终止\\ 0 ,它可能仍然打印预期的输出,因为按照你的字符串是在你的记忆非打印字符。这是一个非常讨厌的错误,虽然,因为它可能炸毁时,你可能不会想到它。 始终终止字符串'\\ 0'

gcc 4.4.4 c89

What is the standard way to null terminate a string? When I use the NULL I get a warning message.

*dest++ = 0; 
*dest++ = '\0'; 
*dest++ = NULL; /* Warning: Assignment takes integer from pointer without a cast */

Source code:

size_t s_strscpy(char *dest, const char *src, const size_t len)
{
    /* Copy the contents from src to dest */
    size_t i = 0;
    for(i = 0; i < len; i++)
    *dest++ = *src++;

    /* Null terminate dest */
     *dest++ = 0; 

    return i;
}

Another question: I deliberately commented out the line that null terminates. However, it still correctly printed out the contents of the dest. The caller of this function would send the length of the string by either included the NULL or not. i.e. strlen(src) + 1 or stlen(src).

size_t s_strscpy(char *dest, const char *src, const size_t len)
{
    /* Copy the contents from src to dest */
    size_t i = 0;
    /* Don't copy the null terminator */
    for(i = 0; i < len - 1; i++)
    *dest++ = *src++;

    /* Don't add the Null terminator */
    /* *dest++ = 0; */

    return i;
}

解决方案

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

这篇关于空终止字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆