The following program finds the sum of the integer numbers in a linked list:
/**
** Example program illustrating structures using linked lists
**/
#include <stdio.h>
struct record {
int number;
struct record *next_num;
};
int main(void)
{
struct record name1, name2, name3;
struct record *recd_pointer = &name1;
int sum = 0;
name1.number = 144;
name2.number = 203;
name3.number = 488;
name1.next_num = &name2;
name2.next_num = &name3;
name3.next_num = NULL;
while (recd_pointer != NULL)
{
sum += recd_pointer->number;
recd_pointer = recd_pointer->next_num;
}
printf("Sum = %d\n", sum);
return(0);
}
The structure type record contains two members: the integer number and next_num, which is a pointer to a structure variable of type record.
The record type variables name1, name2, and name3 are assigned the following values:
| Member | Value |
| name1.number | 144 |
| name1.next_num | address of name2 |
| name2.number | 203 |
| name2.next_num | address of name3 |
| name3.number | 488 |
| name3.next_num | NULL (indicating the end of the linked list) |
The variable recd_pointer is a pointer to a structure of type record. It is initialized to the address of name1 (the beginning of the linked list).
The while loop causes the linked list to be scanned until recd_pointer equals NULL. The statement:
recd_pointer = recd_pointer->next_num;
advances the pointer to the next object in the list.
The following example shows how to define and initialize a structure within a structure.
struct client {
char *name;
struct info {
int age;
int weight;
} pers_info;
} child = { "Bob", { 3, 31 } }; /* initialization */