null terminating a string

前端 未结 4 725
有刺的猬
有刺的猬 2020-11-29 05:48

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++ =          


        
相关标签:
4条回答
  • 2020-11-29 06:13

    From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

    In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

    0 讨论(0)
  • 2020-11-29 06:18

    '\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

    When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

    0 讨论(0)
  • 2020-11-29 06:35

    Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

    char *buffer;
    ...
    buffer[end_position] = '\0';
    

    This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

    buffer[end_position] = 0; 
    
    0 讨论(0)
  • 2020-11-29 06:39

    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'.

    0 讨论(0)
提交回复
热议问题