Why null-terminated strings? Or: null-terminated vs. characters + length storage

后端 未结 10 1293
-上瘾入骨i
-上瘾入骨i 2020-12-23 17:29

I\'m writing a language interpreter in C, and my string type contains a length attribute, like so:

struct String
{
    char* charac         


        
10条回答
  •  一向
    一向 (楼主)
    2020-12-23 17:39

    Lengths have their problems too.

    • The length takes extra storage (not such an issue now, but a big factor 30 years ago).

    • Every time you alter a string you have to update the length, so you get reduced performance across the board.

    • With a NUL-terminated string you can still use a length or store a pointer to the last character, so if you are doing lots of string manipulations, you can still equal the performance of string-with-length.

    • NUL-terminated strings are much simpler - The NUL terminator is just a convention used by methods like strcat to determine the end of the string. So you can store them in a regular char array rather than having to use a struct.

提交回复
热议问题