C Language Learning course seventh chapter-Structure and Union (5)

Source: Internet
Author: User
Tags define null printf

topoic= Dynamic Storage Allocation

In the array chapter, it was introduced that the length of several groups was predefined and fixed throughout the program. Dynamic array types are not allowed in C language. For example: int n;scanf ("%d", &n); int a[n]; It is wrong to represent the length with a variable, to animate the size of the array. However, in actual programming, this is often the case, that is, the required memory space depends on the actual input data, and can not be predetermined. For this kind of problem, the method of using array is difficult to solve. To address the above problems, C language provides some memory management functions that can dynamically allocate memory space as needed, or reclaim unused space for reuse, providing a means to effectively utilize memory resources. The following three memory management functions are commonly used:

1. Allocating memory space functions malloc
Call form: (type specifier *) malloc (size) feature: Allocate a contiguous area in the dynamic storage area of memory with a length of "size" byte. The return value of the function is the first address of the range. The type specifier indicates what data type is used for the zone. (type specifier *) indicates that the return value is cast to the type pointer. ' Size ' is an unsigned number. For example: pc= (char *) malloc (100); Represents a 100-byte allocated memory space and is cast to a character array type, and the return value of the function is a pointer to the character array, which is assigned to the pointer variable PC.

2. Allocating memory space functions Calloc
Calloc is also used to allocate memory space. Invocation form: (type specifier *) calloc (n,size) function: To allocate N-block contiguous regions in the memory dynamic store with a length of "size" bytes. The return value of the function is the first address of the range. (Type descriptor *) is used to force type conversions. The difference between the Calloc function and the malloc function is only that you can allocate n chunks at once. For example: ps= (Struet stu*) calloc (2,sizeof (struct stu)); The sizeof (struct Stu) is the length of the STU structure. So the statement means: Allocate 2 contiguous areas by Stu length, cast to Stu type, and assign the first address to the pointer variable PS.

3. Free memory space function
Call form: Free (VOID*PTR); Function: Frees a block of memory that PTR points to, and PTR is a pointer variable of any type that points to the first address of the freed area. The freed zone should be an area allocated by the malloc or calloc function: [Example 7.9] allocates a region and enters a student data.
Main ()
{
struct STU
{
int num;
Char *name;
char sex;
Float score;
} *ps;
ps= (struct stu*) malloc (sizeof (struct stu));
ps->num=102;
Ps->name= "Zhang Ping";
ps->sex= ' M ';
ps->score=62.5;
printf ("number=%d\nname=%s\n", ps->num,ps->name);
printf ("sex=%c\nscore=%f\n", Ps->sex,ps->score);
Free (PS);
}
In this example, the structure Stu is defined and the STU type pointer variable PS is defined. It then allocates a stu large memory area and assigns the first address to PS so that the PS points to the area. Each member is assigned a value using PS as the pointer variable pointing to the structure, and the member values are output by printf. Finally, use the free function to release the memory space that the PS points to. The whole program includes three steps to apply for memory space, use memory space, free memory space, and realize dynamic allocation of storage space. In example 7.9, the concept of a linked list is used to allocate the memory space for a structure by means of dynamic allocation. Each allocation of space can be used to store a student's data, we can call it a node. How many students should apply for allocating the amount of memory space, that is to say, how many nodes to build. Of course, you can do this with an array of structures, but you cannot determine the size of the array if you cannot accurately grasp the number of students beforehand. And when students fail to repeat and drop out, they cannot release the space occupied by the element from the array. The dynamic storage method can solve these problems well. One student assigns a node that does not need to predetermine the exact number of students, and a student who dropped out of school may delete the node and release the storage space occupied by the node. Thus saving valuable memory resources. On the other hand, an array of methods must occupy a contiguous area of memory. When using dynamic allocation, each node can be discontinuous (contiguous within the node). The connection between nodes can be implemented with pointers. That is, in a node structure, a member item is defined to hold the first address of the next node, which is used to store the member of the address, often referred to as the pointer field. The first address of the second node can be deposited in the pointer field of the primary node, and the first address of the third node is stored in the pointer field of the second node, so that the concatenation continues until the last node. The last node has a pointer field that can be assigned 0 because there is no subsequent node connection. Such a connection is called a "linked list" in the data structure. Figure 7.3 is a schematic of the list.

In Figure 7.3, the No. 0 node is called the header node, which holds the first address of the initial node, which has no data, but a pointer variable. Each of the following nodes is divided into two domains, one is the data field, which holds various actual data, such as number num, name name, gender sex and achievement score etc. Another field is a pointer field that holds the first address of the next node. Each node in a linked list is of the same structure type. For example, a node that holds student numbers and grades should be the following structure:
struct STU
{int num;
int score;
struct Stu *next;
}
The first two member items make up the data field, and the latter member item next forms the Pointer field, which is a pointer variable that points to the Stu type structure. The basic operation of a linked list has the following main operations on the linked list:
1. Establish the linked list;
2. The structure of the search and output;
3. Inserting a node;
4. Delete a node;
Here are examples to illustrate these operations.
[Example 7.10] establish a chain of three nodes that holds student data. For simplicity's sake, we assume that the student data structure has only the number and age.
You can write a function creat to establish a linked list. The procedure is as follows:
#define NULL 0
#define TYPE struct STU
#define LEN sizeof (struct stu)
struct STU
{
int num;
int age;
struct Stu *next;
};
TYPE *creat (int n)
{
struct Stu *HEAD,*PF,*PB;
int i;
for (i=0;i<n;i++)
{
pb= (type*) malloc (LEN);
printf ("Input number and age\n");
scanf ("%d%d", &pb->num,&pb->age);
if (i==0)
PF=HEAD=PB;
else pf->next=pb;
pb->next=null;
PF=PB;
}
return (head);
}
The three symbolic constants are defined outside the function first with a macro definition. Here, type represents struct Stu, and Len means sizeof (struct Stu) The main purpose is to reduce writing and make reading easier in the following programs. struct Stu is defined as an external type, which can be used by various functions in the program.

Related Article

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.