Introduction to C language (22) heap and linked list

Source: Internet
Author: User

Heap and linked list

We often ask in the topic, enter an integer, and then use this integer as the number of elements of the array, the following program code is ErrorOf
int n,array[n];
scanf (%d,&n);
In Turbo C, dynamic arrays are not allowed。 Then, if this is necessary, only the linked list can be used.


One, Heap
A heap is a dynamic storage structure, which is actually a free storage area in a data segment, a name used in the C language, often used for storage allocation of dynamic data. The heap is stored in a data that is always allocated as an integer multiple of 2 bytes, and the address increases in the direction of the change. The heap can be allocated continuously until there is no heap space, or it can be released, redistributed at any time, and there is no order problem.
The so-called dynamic array is to determine the size of the program during the run, such as commonly used dynamic array, they are in the program execution of dynamic changes, that is, in the beginning of the program does not specify the size, only when the program is run with the heap allocation function allocated storage space, the size of the allocation can be based on demand, After this data is used, it frees up the heap space they occupy and can be redistributed.
Heap and stack are used in opposite growth, the stack grows upward, that is, to the small address direction growth, and the heap downward growth, that is, to the large address direction, the rest of the free space in the meantime. The use of the process to prevent excessive growth and lead to coverage.
General program we are all using small memory mode, its memory allocation is as follows:
________________
| Code Snippets |
| ———————— |
| Data Segment |
| ———————— |
| BSS Segment |
| ———————— |
| Heap |
|----------------| Free space
|----------------|
| Stack |
| ———————— |
| Far heap |
|----------------|
|________________| Free space

There is free space between the heap and the stack, as well as the far heap address, which is a total of 64K.
Heap management functions:
1. Get the free space between heap and stack function
Small Data memory mode: unsigned coreleft (void);
Big Data Memory mode: unsigned long coreleft (void);
For far heaps, you can use the Farcoreleft () function.
2. Assigning a heap space function
void malloc (unsigned size);
The function allocates a heap space of size bytes and returns a pointer to that space. Because this pointer is void, you must cast the pointer when it is assigned to another type of pointer. For example, info is a struct-type pointer, i.e.:
struct addr *info;
When assigning a pointer returned by the malloc () function to info, type conversions must be made:
info= (struct addr *) malloc (sizeof (record));
The heap space allocated by the malloc () function will not be initialized. When the malloc () function is called, the function returns a null pointer if there is no memory space available at the time.
3. Allocate a heap space whose size is a function that can hold several elements, without element length of size
void calloc (unsigned n,unsigned size);
The function allocates a heap space of size n*size and initializes the allocated space with 0. The function returns a pointer to the allocated space, and returns a null pointer when no space is available.
4. Redistributing Heap space functions
void *realloc (void *ptr,unsigned newsize);
The function will reassign the heap space pointed to by PTR and change the size to newsize.
5. Releasing the heap space function
void free (void *ptr);
Here is a comprehensive example of heaps and stacks:
void push (int), int pop (), int *pi,*tos;main () {int v;pi= (int *), malloc (50*sizeof (int)), if (!PI) {printf (allocation failure\n); exit (0);} tos=pi;do{printf (value,push it;enter 0 then pops; (Enter-1 then stop) \ n); scanf (%d,&v); if (v!=0) push (v); else printf (pop this is it%d\n,pop ());} while (v!=-1);} void push (int i) {pi++;if (pi== (tos+50)) {printf (stack overflow\n); exit (0);} *pi=i;} int pop () {if (Pi==tos) {printf (stack underflow\n); exit (0);} Pi--;return * (pi+1);}
The program allocates 100 bytes of heap space, converts it to an int type to assign pi, and when pi is null, indicates that there is no space available, then allocation failure is displayed. Enter an integer that is pressed into the stack and displays stack overflow when it is more than 50 o'clock. When you enter 0 o'clock, the data in the stack pops up. This program also demonstrates the feature of the last-in-first-out of the stack.


second, linked list
The heap is used to store dynamic data. The most typical example of dynamic data is linked lists.
Image said: A number of data items are linked to a certain principle, there is no data item has a pointer to the next data, the data items are linked to a table by the pointer, the last data does not have a pointer (pointer is NULL), this is the linked list. You can see that the list is placed in memory, and not necessarily as an array, continuous storage, can also be stored separately. Because each node of the chain has an address pointing to the next node, to find a node, you must find the previous node, and so on, you can find the destination point from the first node. Linked lists are used more widely in database establishment and management.
Each node in the list has the same structure type, which consists of two parts, the data part (which contains some useful information), and the other is the pointer to the chain. The following defines a data structure for a communication chain node:
struct Address{char name[30];char Street[40];char city[20];char state[10];char zip[6];struct address *next;/*pointer to Next entry*/}list_entry;
The first five members of the structure are the information part of the node, and the last member is a pointer to the same struct type. That is, next points to a node of the same struct type.

1. Create a linked list
When a linked list is established, the first node's contents are stored in the heap, and the first address of the memory area in the heap that can be stored in the node is assigned to a pointer. We can use the malloc () function to allocate memory areas. If info is a pointer:
info= (struct address *) malloc (sizeof (list_entry));
When the first node is stored in the memory area indicated by info, and then executes the function, it gets the store address info of the narrow node, at which point the info is assigned to the previous node's next, and the contents of the node are stored in the memory area indicated by info, so that the two nodes are linked together. This process is repeated several times, you can continue to join the node to the end of the list.
 #include Stdlib.h#include alloc.h#include stdio.h#include string.hstruct address{char name[30];char Street[40];char city[20]; Char State[10];char zip[6];struct address *next;} List_entry;void inputs (char *,char *,int), void Dls_store (struct address*), main () {struct address *info;int i;for (i=0;i <5;i++) {info= (struct address *) malloc (sizeof (list_entry)); inputs (enter name:,info->name,30); inputs (enter STREET:,INFO->STREET,40); inputs (enter city:,info->city,20); inputs (enter state:,info->state,10); inputs ( Enter zip:,info->zip,6);d Ls_store (info);}} void inputs (char *prompt,char *s,int count) {char p[255];d o{printf (prompt), gets (p), if (strlen (p) >count) printf (\ n Too long \ n);} while (Strlen (p) >count); strcpy (s,p);} void Dls_store (struct address *in) {static struct address *last=null;if (!last) Last=in;else last->next=in;in-> Next=null;last=in;} 
The inputs () function is relatively simple and does not explain it.
The Dls_store () function is the next pointer item that writes the input node address to the previous node. The struct pointer defined in the last is a static variable with an initial value of NULL, which means that the variable is assigned a fixed storage space at compile time to hold its value. Because the initial value is null, so that when the function is first called, because it represents a null pointer, it assigns the first node address allocated by malloc () to it, so that last points to that node, and when the second call is made, the static variable has pointed to the first node address. So repeated calls, then set up n calls produced by n nodes of the chain (the subject n=5).

2. Insertion and deletion of chain data
For a sorted list (assuming a sequence), now you want to insert a data into it, there are three possible scenarios:
(1). Smaller than the first data, that is, the inserted data appears as the first item:
In this case, our approach is to use this data as the first item, and the pointer points to the original first item. Set the original first item to top and the data to be inserted as in, then:
in->next=top;
You can make the data the head of the list.
(2). Larger than the last item, that is, the inserted data appears as the last item:
This is also very good, set the original last item is old, then:
old->next=in;
in->next=null;
(3). As an intermediate item appears: Front is old, followed by top, then:
old->next=in;
in->next=top;
If you want to delete a data, it may also appear at the beginning, middle, and end.
For example, to delete in this data, it was originally in front of old, followed by top, that is, the original linked list is this:
old->next=in;
in->next=top;
Now delete in, just point old to top:
old->next=top->next;
/* Delete node function */void Delete (struct address *info,struct address *old) {if (info) {if (Info==start) start=info->next;/* Remove the first node */else{old->next=info->next;/* Pointer to the next node before the node is deleted */last=old;/* If the node is a linked footer, the node pointer before the node points to Null*/}free (info ); /* Release Delete node footprint */}}
/* Find the data in the list */struct address *search (struct address *top,char *n) {while (top) {if (!strcmp (n,top->name)) return top; /* Locate the node pointer you want to delete */top=top->next; /* Continue to find */}return NULL; /* Not found */}
/* Output */void display (struct address *top) {while (top) {printf (top->name); top=top->next;}}


The problem of linked list is more complicated, but it is also very important concept. The above-mentioned input, find, delete, insert and other functions must be understood, you can refer to some other information to see.

The single-linked list above, but the single-linked list has one drawback, is that it cannot be reversed, when a chain broken due to damage, the entire chain is destroyed and can not be restored. Doubly linked list can compensate for this disadvantage, so-called doubly linked list refers to each node has two pointer items, one pointer to its front node, and the other pointer to the back node. About the use of doubly linked list is relatively complex, here is not introduced, you can find some other information to see.

Introduction to C language (22) heap and linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.