Indefinite-length array as member of struct: how?

Phil Cornes pc at cs.keele.ac.uk
Sat Jul 15 00:23:15 AEST 1989


>From article <23282 at iuvax.cs.indiana.edu>, by bobmon at iuvax.cs.indiana.edu (RAMontante):
> Go ahead and flame me.  I learn more from my failures than from my
> successes...

With a structure declaration:

	struct node1 {
		struct node1 *next1;
		char string1[1];
	} *nodeptr1;

and a block of code:

	nodeptr1=(struct node1 *)malloc(sizeof(struct node1)+strlen(data));
	(void)strcpy(nodeptr1->string1,data);

you end up with a memory layout as you suggest:
 
         .-------------v--------------- - - - --.
         | ptr to next | "I AM A STRING . . . " |
         `-------------^--------------- - - - --'
 
In this case the expression:

	nodeptr1->string1

evaluates to a pointer constant to the first (and only declared) element
of the string1 array. Accessing a single character in the stored data string
(say the 'M') can be done as follows:

	nodeptr1->string1[3]

On the other hand, with a structure declared as:

	struct node2 {
		struct node2 *next2;
		char *string2;
	} nodeptr2;

and a block of code like:

	nodeptr2=(struct node2 *)malloc(sizeof(struct node2)+strlen(data)+1);
	nodeptr2->string2 = (char *)nodeptr2+sizeof(struct node2);
	(void)strcpy(nodeptr2->string2,data);

you end up with the memory laid out again as you suggest:
 
         .-------------v---------------v--------------- - - - --.
         | ptr to next | ptr to string | "I AM A STRING . . . " |
         `-------------^---------------^--------------- - - - --'
 
These two may look very different but you will find that they don't behave
so in programs.  Once again, the expression:

	nodeptr2->string2

is a pointer to the first element of the string2 array. Accessing a single
character in the stored data string (say the 'M') can be done as follows:

	nodeptr2->string2[3]

As you can see this is the same as the first example. My own preference in
this case is to use the second of these solutions for two reasons:

1. The first solution relies upon a lot more knowledge of the way that C
   operates internally, in order to be confident that it will work.

2. The first solution also suffers from the problem that it relies upon
   accessing the string1 array outside its declared subscript range,
   which must be classed as a 'tacky' practice at best.

So, no flames... you pays your money and you takes your choice!!!


Phil Cornes      I just called to say .....
-----------*
                 JANET: cdtpc at uk.ac.stafpol.cr83
                 Phone: +44 (0)785 53511 x6058
                 Smail: Staffordshire Polytechnic, Computing Department
                        Blackheath Lane, STAFFORD, ST18 0AD, ENGLAND.



More information about the Comp.lang.c mailing list