Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!apple!ames!haven!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Keywords: char string [] [0] [1] Message-ID: <18537@mimsy.UUCP> Date: 14 Jul 89 00:57:26 GMT References: <23282@iuvax.cs.indiana.edu> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 57 In article <23282@iuvax.cs.indiana.edu> bobmon@iuvax.cs.indiana.edu (RAMontante) writes: [in re changing struct node { struct node *next; char string[?]; }; for some `?' to struct node { struct node *next; char *string; }; ] >Don't these result in a chunk of memory that looks like: > > .-------------v---------------v--------------- - - - --. > | ptr to next | ptr to string | "I AM A STRING . . . " | > `-------------^---------------^--------------- - - - --' > >where the second field (ptr to string) just points to the third? >I would think the desired memory chunk would look like: > > .-------------v--------------- - - - --. > | ptr to next | "I AM A STRING . . . " | > `-------------^--------------- - - - --' This is largely correct. What is somewhat misleading is the phrase `second field (ptr to string) ... points to the third.' The second field is a pointer to char, not a pointer to string. When it points to a character that is the first of an array of characters, where that array is formed of a series of values other than '\0' whose end is marked by one (or more) '\0' values, people generally say that the pointer `points to a string', but it really points to one character. >In the [char *string] case, I access the string with "*(nodeptr->string)". No: *nodeptr->string (the parentheses are unnecessary) gets you the character to which `string' points: one object of type char. Without the `*' it gets you an object of type `pointer to char', which in this example points to the first character of a C-style string. >[with char string[SOMESIZE]] I just use "nodeptr->string". This names an object of type `array SOMESIZE of char'. In rvalue contexts, such as printf("%s\n", nodeptr->string); the array-object converts to an object of type `pointer to char', which points to the first character of that array---in this example, the first character of a C-style string. Given either declaration, one uses the name `nodeptr->string' in the same way in rvalue contexts. The difference between the two declarations appears only in lvaue contexts (including `sizeof') and in the actual memory layout (as you illustrated above). -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris