C struct hack at work

Yes, that is (and was) the standard way in C to create and process a variably-sized struct.

That example is a bit verbose. Most programmers would handle it more deftly:

struct mystruct {
        int len;
        char chararray[1];  // some compilers would allow [0] here
    };
    char *msg = "abcdefghi";
    int n = strlen (msg);

    struct mystruct *ptr = malloc(sizeof(struct mystruct) + n + 1);

    ptr->len = n;
    strcpy (ptr->chararray, msg);
}

Leave a Comment