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

后端 未结 10 1317
-上瘾入骨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:32

    The usual solution is to do both - keep the length and maintain the null terminator. It's not much extra work and means that you are always ready to pass the string to any function.

    Null-terminated strings are often a drain on performance, for the obvious reason that the time taken to discover the length depends on the length. On the plus side, they are the standard way of representing strings in C, so you have little choice but to support them if you want to use most C libraries.

提交回复
热议问题