C struct hack at work

后端 未结 4 1441
野趣味
野趣味 2020-11-28 06:39

Is this how one can use the the \"extra\" memory allocated while using the C struct hack?

Questions:

I have a C struct hack implementation below. My questio

4条回答
  •  庸人自扰
    2020-11-28 06:51

    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);
    }
    

提交回复
热议问题