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

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

    Although I prefer the array + len method in most cases, there are valid reasons for using null-terminated.

    Take a 32-bit system.

    To store a 7 byte string
    char * + size_t + 8 bytes = 19 bytes

    To store a 7 byte null-term string
    char * + 8 = 16 bytes.

    null-term arrays don't need to be immutable like your strings do. I can happily truncate the c-string by simply places a null char. If you code, you would need to create a new string, which involves allocating memory.

    Depending on the usage of the strings, your strings will never be able to match the performance possible with c-strings as opposed to your strings.

提交回复
热议问题