C struct hack at work -
is how 1 can use the "extra" memory allocated while using c struct hack?
questions:
i have c struct hack implementation below. question how can use "extra" memory have allocated hack. can please give me example on using memory ?
#include<stdio.h> #include<stdlib.h> int main() { struct mystruct { int len; char chararray[1]; }; struct mystruct *ptr = malloc(sizeof(struct mystruct) + 10 - 1); ptr->len=10; ptr->chararray[0] = 'a'; ptr->chararray[1] = 'b'; ptr->chararray[2] = 'c'; ptr->chararray[3] = 'd'; ptr->chararray[4] = 'e'; ptr->chararray[5] = 'f'; ptr->chararray[6] = 'g'; ptr->chararray[7] = 'h'; ptr->chararray[8] = 'i'; ptr->chararray[9] = 'j'; }
yes, (and was) standard way in c
create , process variably-sized struct
.
that example bit verbose. programmers handle more deftly:
struct mystruct { int len; char chararray[1]; // compilers 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); }
Comments
Post a Comment