Dynamic structures in C

ee161acv at sdccs5.UUCP ee161acv at sdccs5.UUCP
Sat Mar 3 03:19:35 AEST 1984




	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



More information about the Comp.lang.c mailing list