• We can define structures with pointer fields that refer to the structure type containing them
•
•
•
•
struct list { int data; struct list *next;
}
• data
next
• The pointer variable next is called a link. Each structure is linked to a succeeding structure by way of the field next. The pointer variable next contains an address of either the location in memory of the successor struct list element or the special value NULL.
• Example
•
•
•
•
•
•
•
struct list a, b, c;
a.data = 1;
b.data = 2;
c.data = 3;
a.next = b.next = c.next = NULL;
• a
• 1
• NULL
• data • next
• b
• 2
• NULL
• data • next
• c
• 3
NULL
• data • next
• Example continues
•
•
•
•
•
a.next
b.next
a.next
a.next
b.next
• a
• 1
= &b;
= &c;
-> data has value 2
-> next -> data has value 3
-> next -> data error !!
• b
• 2
• c
• 3
• Dynamic Memory Allocation
• Creating and maintaining dynamic data structures requires dynamic memory allocation – the ability for a program to obtain more memory space at execution time to hold new values, and to release space no longer needed.
• In C, functions malloc and free, and operator sizeof are essential to dynamic memory allocation.
• Dynamic Memory Operators sizeof and malloc
• Unary operator sizeof is used to determine the size in bytes of any data type. • sizeof(double) sizeof(int)
• Function malloc takes as an argument the number of bytes to be allocated and return a pointer of type void * to the allocated memory. (A void * pointer may be assigned to a variable of any pointer type. ) It is normally used with the sizeof operator.
• Dynamic Memory Operators in C Example
•
•
•
•
•
•
•
•
struct node{ int data; struct node *next;
};
struct node *ptr; ptr = (struct node *) /*type casting */ malloc(sizeof(struct node));
• ptr
• ?
• ?
• The Free Operator in C