What are the problems of a zero-terminated string that length-prefixed strings overcome?

后端 未结 6 1771
滥情空心
滥情空心 2021-02-06 21:57

What are the problems of a zero-terminated string that length-prefixed strings overcome?

I was reading the book Write Great Code vol. 1 and I had that question in mind.<

6条回答
  •  一向
    一向 (楼主)
    2021-02-06 22:37

    What are the problems of a zero-terminated string that length-prefixed strings overcome?

    None whatsoever.
    It's just eye candy.

    Length-prefixed strings have, as part of their structure, information on how long the string is. If you want to do the same with zero-terminated strings you can use a helper variable;

    lpstring = "foobar"; // saves '6' somewhere "inside" lpstring
    
    ztstring = "foobar";
    ztlength = 6;        // saves '6' in a helper variable
    

    Lots of C library functions work with zero-terminated strings and cannot use anything past the '\0' byte. That's an issue with the functions themselves, not the string structure. If you need functions which deal with zero-terminated strings with embedded zeroes, write your own.

提交回复
热议问题