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

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

    One advantage of nul-terminated strings is that if you are walking through a string character-by-character, you only need to keep a single pointer to address the string:

    while (*s)
    {
        *s = toupper(*s);
        s++;
    }
    

    whereas for strings without sentinels, you need to keep two bits of state around: either a pointer and index:

    while (i < s.length)
    {
        s.data[i] = toupper(s.data[i]);
        i++;
    }
    

    ...or a current pointer and a limit:

    s_end = s + length;
    while (s < s_end)
    {
        *s = toupper(*s);
        s++;
    }
    

    When CPU registers were a scarce resource (and compilers were worse at allocating them), this was important. Now, not so much.

提交回复
热议问题