Declaring Pascal-style strings in C

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

    My approach would be to create functions for dealing with Pascal strings:

    void cstr2pstr(const char *cstr, char *pstr) {
        int i;
        for (i = 0; cstr[i]; i++) {
            pstr[i+1] = cstr[i];
        }
        pstr[0] = i;
    }
    
    void pstr2cstr(const char *pstr, char *cstr) {
        int i;
        for (i = 0; i < pstr[0]; i++) {
            cstr[i] = pstr[i+1];
        }
        cstr[i] = 0;
    }
    

    Then I could use it this way:

    int main(int arg, char *argv[]) {
        char cstr[] = "ABCD", pstr[5], back[5];
        cstr2pstr(cstr, pstr);
        pstr2cstr(pstr, back);
        printf("%s\n", back);
        return 0;
    }
    

    This seems to be simple, straightforward, less error prone and not specially awkward. It may be not the solution to your problem, but I would recommend you to at least think about using it.

提交回复
热议问题