Declaring Pascal-style strings in C

后端 未结 10 1281
渐次进展
渐次进展 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:43

    This is why Variable Length Arrays were introduced in c99 (and to avoid the use of the "struct hack") IIRC, Pascal-strings were limited to a maximal length of 255.

    #include 
    #include 
    #include 
    #include  // For CHAR_BIT
    
    struct pstring {
            unsigned char len;
            char dat[];
            };
    
    struct pstring *pstring_new(char *src, size_t len)
    {
    struct pstring *this;
    if (!len) len = strlen(src);
    
        /* if the size does not fit in the ->len field: just truncate ... */
    if (len >=(1u << (CHAR_BIT * sizeof this->len))) len = (1u << (CHAR_BIT * sizeof this->len))-1;
    
    this = malloc(sizeof *this + len);
    if (!this) return NULL;
    
    this->len = len;
    memcpy (this->dat, src, len);
    return this;
    }
    
    int main(void)
    {
    struct pstring *pp;
    
    pp = pstring_new("Hello, world!", 0);
    
    printf("%p:[%u], %*.*s\n", (void*) pp
            , (unsigned int) pp->len
            , (unsigned int) pp->len
            , (unsigned int) pp->len
            , pp->dat
            );
    return 0;
    }
    

提交回复
热议问题