Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c - null terminating a string

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++ = ''; 
*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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To your first question: I would go with Paul R's comment and terminate with ''. 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, 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 ''.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...