Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83; site sdccs5.UUCP Path: utzoo!watmath!clyde!floyd!harpo!decvax!ittvax!dcdwest!sdcsvax!sdccs5!ee161acv From: ee161acv@sdccs5.UUCP Newsgroups: net.lang.c Subject: Dynamic structures in C Message-ID: <1158@sdccs5.UUCP> Date: Fri, 2-Mar-84 12:19:35 EST Article-I.D.: sdccs5.1158 Posted: Fri Mar 2 12:19:35 1984 Date-Received: Sat, 3-Mar-84 23:50:05 EST Organization: U.C. San Diego, Computer Center Lines: 90 I want to have an element in a structure that points to the end of the structure, but I don't want any space allocated by 'C' for that element. The reason for this is that I want the structure to have varying sizes, with the size depending on certain other parameters. The following is the kind of thing I want: ------------------------------ struct stuff { int numchars; /* Size of remainder of structure */ char chars[]; /* Allocate numchars chars for this element */ /*###6 [cc] warning: illegal zero sized structure member: chars%%%*/ }; main () { int num; /* User input */ struct stuff *block; /* -> node to allocate */ printf ("How many characters to allocate? "); scanf ("%d", &num); /* Request info */ block = (struct stuff *)calloc(1, sizeof(struct stuff) + num); /* Allocate enough memory for the structure and the extra bytes */ block->numchars = num; /* Etc. */ /* block->chars[0] = ... */ } ------------------------------ Of course this program runs (the warning does not stop it from compiling), but I also want to suppress the warning. Is there any provision in C to allow me to do this? Of course, I want the character string to be stored WITHIN the structure (as above) and NOT a character pointer to some string outside the structure. Also, I can't say that the end of the string is the first '\0' character, because I want them to be allowed in the string. In the mean time, I was able to solve the problem (with a bit of a comprimise on neatness) with this: ------------------------------ #define FUDGEFACTOR sizeof(char *) #define SIZEOF(type) (sizeof(type) - FUDGEFACTOR) struct stuff { int numchars; /* Size of remainder of structure */ char chars[FUDGEFACTOR]; /* Allocate numchars chars for this element */ }; main () { int num; /* User input */ struct stuff *block; /* -> node to allocate */ printf ("How many characters to allocate? "); scanf ("%d", &num); /* Request info */ block = (struct stuff *)calloc(1, SIZEOF(struct stuff) + num); /* Allocate enough memory for the structure and the extra bytes */ block->numchars = num; /* Etc. */ /* block->chars[0] = ... */ } ------------------------------------ I would like to find a better way. Thanks for any suggestions, Victor Romano. P. S. I also noticed that the directory files on 4.2 use dynamic structure sizes as well, so there's one application of this! ========= Meek and obedient you follow the leader down well trodden corridors into the valley of steel! -PF