In article <fg************ **************@ individual.net>
Francois Grieu <fg****@francen et.fr> wrote:
Given that next is the first field in struct node,
and head is a pointer to node,
does assigning ((node*)&head)->next safely assign head ?
Illustration (this code works on many platforms)
I would be surprised to find a platform on which this does *not*
work:
#include <stdlib.h>
#include <stdio.h>
/* node structure for linked list */
typedef struct node
{
struct node* next;
char payload;
} node;
int main(void)
{
node *head, *last, *temp;
int c;
/* build list from stdin */
last = (node*)&head;
while ((c = getchar())!=EOF )
{
if ((temp = malloc(sizeof(n ode)))==NULL)
return 1;
temp->payload = c;
last->next = temp;
last = temp;
}
last->next = NULL;
[etc]
But there is no need to resort to such subterfuge. Simply use
pointers the way they are intended:
node *head, *temp;
node **npp = &head;
while ((c = getchar()) != EOF) {
temp = malloc(sizeof *temp);
if (temp == NULL)
return EXIT_FAILURE;
temp->payload = c;
*npp = temp;
npp = &temp->next;
}
*npp = NULL;
While the head is just a pointer (of type "struct node *", aka
"node *"), each node also contains a pointer of that same type.
If we point a separate pointer ("npp") at each pointer in turn, we
can set each pointed-to pointer with absolute 100% guaranteed
safety, even though the "head" pointer is *just* a pointer, and
the other pointers are elements of a larger collection.
Naturally, to point to "struct node *" objects, we need a pointer
of type "struct node **" (aka "node **").
Note that this code continues to work even if the "next" field is
moved elsewhere in the list structure -- while the original code,
with its cast, stops working.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.