Evaluation order of assignment.
Larry Miller
lmiller at venera.isi.edu
Thu Aug 18 03:47:04 AEST 1988
In article <957 at orion.cf.uci.edu> schmidt at bonnie.ics.uci.edu (Douglas C. Schmidt) writes:
>Hi,
>
> Assume the following recursive type declaration for a linked
>list:
>
>struct list {
> int item;
> struct list *next;
>};
>
>Is the following always guaranteed to produce the "intended"
>result:
>
>...
>struct list foo() (1)
>{ (2)
> struct list head; (3)
>
> return(head->next = head = (struct list *) malloc(sizeof(struct list))); (4)
>} (5)
>...
>
>My intention is to create a dummy node in a circularly-linked list,
>and assign the dummy node's next field to point to the head of
>the list. Since assignment associates from right-to-left this
>will alway work, right (cryptic style notwithstanding !! ;-)).
[Line numbers added].
Well, let's see, it's not clear what you want to return, an entire structure
(struct list), or a pointer to one. The usual way that a routine such as this
is written is to return a POINTER to one, so line (1) probably should be
struct list * foo()
There are several problems at line (4):
You correctly cast the return from malloc, but you have a type mis-
match. head is type (struct list). You've cast the return from
malloc to be a (struct list *). What you wanted to do was to
declare head to be a struct list * at line (3):
struct list *head;
Assuming this new correct definition/declaration of head, you still
risk a NULL return from malloc, so the reference through head to
head->next could produce an illegal pointer reference through NULL.
Finally, you're returning head->next, a (struct list *), but you
originally declared foo() to return a struct list.
Your explanation of what you want done won't work even with the fixes
described above, since when you're done what you'll get is a pointer
to a (struct list), with its next field pointing back to itself:
+---------+------+
| item | next +-----+
+---------+------+ |
^ |
| |
+--------------------+
Larry Miller lmiller at venera.isi.edu (no uucp)
USC/ISI 213-822-1511
4676 Admiralty Way
Marina del Rey, CA. 90292
More information about the Comp.lang.c
mailing list