Indefinite-length array as member of struct: how?
Chris Torek
chris at mimsy.UUCP
Fri Jul 14 10:57:26 AEST 1989
In article <23282 at iuvax.cs.indiana.edu> bobmon at 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 at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list