Declaring Pascal-style strings in C

后端 未结 10 1233
渐次进展
渐次进展 2020-12-25 13:18

In C, is there a good way to define length first, Pascal-style strings as constants, so they can be placed in ROM? (I\'m working with a small embedded system with a non-GCC

10条回答
  •  礼貌的吻别
    2020-12-25 13:40

    Here's my answer, complete with an append operation that uses alloca() for automatic storage.

    #include 
    #include 
    #include 
    
    struct pstr {
      unsigned length;
      char *cstr;
    };
    
    #define PSTR(x) ((struct pstr){sizeof x - 1, x})
    
    struct pstr pstr_append (struct pstr out,
                 const struct pstr a,
                 const struct pstr b)
    {
      memcpy(out.cstr, a.cstr, a.length); 
      memcpy(out.cstr + a.length, b.cstr, b.length + 1); 
      out.length = a.length + b.length;
      return out;
    }
    
    #define PSTR_APPEND(a,b) \
      pstr_append((struct pstr){0, alloca(a.length + b.length + 1)}, a, b)
    
    int main()
    {
      struct pstr a = PSTR("Hello, Pascal!");
      struct pstr b = PSTR("I didn't C you there.");
    
      struct pstr result = PSTR_APPEND(PSTR_APPEND(a, PSTR(" ")), b);
    
      printf("\"%s\" is %d chars long.\n", result.cstr, result.length);
      return 0;
    } 
    

    You could accomplish the same thing using c strings and strlen. Because both alloca and strlen prefer short strings I think that would make more sense.

提交回复
热议问题