F
Francois Grieu
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)
#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(node)))==NULL)
return 1;
temp->payload = c;
last->next = temp;
last = temp;
}
last->next = NULL;
/* then output list */
temp = head;
while (temp!=NULL)
{
putchar(temp->payload);
temp = temp->next;
}
return 0;
}
and head is a pointer to node,
does assigning ((node*)&head)->next safely assign head ?
Illustration (this code works on many platforms)
#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(node)))==NULL)
return 1;
temp->payload = c;
last->next = temp;
last = temp;
}
last->next = NULL;
/* then output list */
temp = head;
while (temp!=NULL)
{
putchar(temp->payload);
temp = temp->next;
}
return 0;
}