In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of how to use the structure and common body in the C language, the content is detailed and easy to understand, the operation is simple and quick, and has a certain reference value. I believe you will gain something after reading this article on how to use the structure and common body in the C language. Let's take a look.
Structure / struct
Definition of structure
The general form of declaring a structure type is:
Struct structure name {member list}
Among them, a type declaration should be made for each member in the member list, that is:
Type name member name
For example, we need to record the data of a student (student) in the program, including student number (num), name (name), gender (sex), age (age), grade (score), address (addr), etc., as shown in the following figure:
If you want to represent the data structure in the diagram, but the C language does not provide this ready-made data type, so we need to define a structure type to represent it.
Truct student {int num; char name [20]; char sex; int age; float score; char addr [30];}
This defines a new struct type struct student (note that struct is the key to declaring a struct type and cannot be omitted), which declares to the compiler that it is a "struct type" that includes different types of data items such as num, name, sex, age, score, addr, and so on.
It should be said that the struct student here is a type name, which has the same function as the standard types provided by the system (such as int, char, float, double, etc.), and can be used to define the type of variable.
Structural variable
The previous declaration is just a structure type, which is equivalent to a model, but there is no specific data in it, and the compiler does not allocate actual memory units to it. In order to use the data of the structure type in the program, we should define the variable of the structure type and store the specific data in it. Structure type variables are defined in the following 3 ways:
Declare the structure type first, and then define the variable name
Structure type name structure variable name
For example, if we have defined a struct type struct student above, we can use it to declare variables:
Struct student student1, student2
Student1 and student2 are defined as variables of type struct student, and they have the structure of type struct student, which we can initialize later.
Define variables while declaring the type, for example:
Struct student {int num; char name [20]; char sex; int age; float score; char addr [30];} student1, student2
It works the same as the first method, which defines two variables of type struct student, student1 and student2. The general form of definition of this form is:
Struct structure name {member list} variable name list
Directly define the structure type variable, which omits the structure name, and generally takes the following form:
Struct {member list} variable name list
With regard to the type of structure, there is one additional point to note:
Types and variables are different concepts, so don't be confused. We can only assign, access, or operate on variables, not on a type. At compile time, no space is allocated for types, only for variables.
In a nutshell, we can understand "structure type" and "structure variable" as the concepts of "class" and "object" in object-oriented language.
In addition, a member of a structure can also be a structure variable. For example, we first declare a structure struct date:
Struct date {int month; int day; int year;}
Then apply it to the declaration struct student:
Struct student {int num; char name [20]; char sex; int age; float score; struct date birthday; char addr [30];} student1, student2
Finally, explain a point that is easily questionable when reading large open source code (such as Objective-C Runtime source code): the variables declared by the following two structures, SampleA and SampleB, are actually exactly the same in memory, because the structure itself does not carry any additional information:
Struct SampleA {int a; int b; int c;}; struct SampleB {int a; struct Part1 {int b;}; struct Part2 {int c;};}
References to structural volume variables
The way to reference a member in a structural body variable is:
The name of the structure variable. Member name
For example, student1.num represents the num member of the student1 variable, and we can assign the member of the structure variable: student1.num = 10010;.
If the member itself belongs to a struct type, use several member operators (period.) to find the lowest level of members, such as:
Student1.birthday.month = 9
In addition, the members of the structure variable can be operated like ordinary variables, or the address operator can be used to refer to the address of the member of the structure variable, or the address of the structure variable.
Initialization of structural variables
As with other types of variables, structural variables can be defined with their initial values, enclosed in curly braces:
Struct student {int num; char name [20]; char sex; int age; char addr [30];} a = {10010, "Li Lei", 'masking, 18, "Beijing Haidian"}
Structures and arrays
If the element of an array is a struct type, it is called a struct array. The structure array differs from the numeric array introduced earlier in that each array element is data of a structure type, and they all include individual member items.
Define an array of structures
Similar to defining a structure variable, you can declare it as an array, for example:
Struct student {int num; char name [20]; char sex; int age; float score; char addr [30];}; struct student stu [3]
An array stu is defined above. The array has three elements, all of which are of type struct student data, as shown in the following figure:
Initialization of structure array
As with other types of arrays, an array of structures can be initialized, for example:
Struct student {int num; char name [20]; char sex; int age; float score; char addr [30] } stu [3] = {{10101, "Li Lin",'Li Lin, 18,87.5, "Beijing"}, {10102, "Amey", 'Shanghai, 17,92, "Shanghai"}, {10103, "Bingo",' Flying, 20,100, "Fujian"}
As you can see from the above, the general form of initialization of a structure array is to add "= {initial table column};" after the definition array.
The elements in the structure array are also stored continuously in memory, as shown in the following figure:
Structure and pointer
The pointer to a structure variable is the starting address of the memory segment that the variable occupies. You can set a pointer variable to point to a structure variable whose value is the starting address of the structure variable. Pointer variables can also be used to point to elements in an array of structures.
A pointer to a structural variable
Struct student {int num; char name [20]; char sex; int age; float score; char addr [30];}; struct student stu1 = {...}; struct student * p; p = & stu1
The above code first declares the struct student structure type, then defines a variable stu1 of type struct student, and then defines a pointer variable p, which points to data of type struct student, and finally assigns the starting address of the structure variable stu1 to the pointer variable p, as shown in the figure:
At this point, you can use * p to access the value of the structure variable stu1, and (* p) .num to access the member variables of stu. In order to be easy to use and intuitive, the definition of C language can replace (* p). Num with p-> num, which represents the num member of the structure variable that p points to.
In other words, the following three forms are equivalent:
Structural body variable. Member name: stu1.num
(* pointer variable name). Member name: (* p) .num
Pointer variable name-> member name: P-> num
Pointers to struct arrays can also be pointed to by pointer variables for struct arrays and their elements, for example:
Struct student {int num; char name [20]; char sex; int age; float score; char addr [30];} Struct student stu [3] = {{10101, "Li Lin",'Li Lin, 18,87.5, "Beijing"}, {10102, "Amey", 'Shanghai, 17,92, "Shanghai"}, {10103, "Bingo",' Flying, 20,100, "Fujian"}}; struct student * p = stu
At this point, the pointer variable p points to the address of the first element of the array, & stu [0], that is, the array name stu.
Structure pointer usage scene
(1) function parameter: pass the address of the structure variable (or array) to the parameter by using the pointer pointing to the structure variable (or array) as the argument.
Void printStudentInfo (struct student * p)
Because if we directly use the structure variable (not the structure pointer) as the argument, because we adopt the way of "value transfer", all the contents of the memory units occupied by the structure variable are passed to the formal parameter in order. the formal parameter must also be the same type of structural variable.
During the function call, the formal parameter also occupies the memory unit, which will not only bring great time and space overhead, but also not conducive to changing the value (result) of the formal parameter structure to the main tone function during the function execution. therefore, it is less common to directly "use structure variables as arguments", but in the form of pointers instead.
(2) linked list
Linked list is a common and important data structure, which is generally used for dynamic storage allocation. The common ones are single-linked list and double-linked list. You can generally use structure to represent the nodes of the linked list. The following is the declaration of the common "single-linked list" node:
Struct ListNode {int val; struct ListNode * next;}
Where the value of the val form linked list node and the next pointer are used to point to the next node of the linked list.
For example, the topic of "reverse single linked list" that is more often examined in the interview:
Struct ListNode * reverseList (struct ListNode * head) {if (head = = NULL) {return NULL;} if (head- > next = = NULL) {return head;} struct ListNode * reversedHead = NULL; struct ListNode * prevNode = NULL; struct ListNode * currentNode = head; while (currentNode! = NULL) {struct ListNode * nextNode = currentNode- > next If (nextNode = = NULL) {reversedHead = currentNode;} currentNode- > next = prevNode; prevNode = currentNode; currentNode = nextNode;} return reversedHead;}
(3) binary tree
Struct TreeNode {int val; struct TreeNode * left; struct TreeNode * right;}
Where val represents the value of the binary tree leaf node, left points to the left subtree of the node, and right points to the right subtree.
For example, the topic of "flipping the binary tree" in the previous buzz about the Google interview:
Struct TreeNode * invertTree (struct TreeNode * root) {if (root = = NULL) {return NULL;} root- > left = invertTree (root- > left); root- > right = invertTree (root- > right); struct TreeNode * temp = root- > left; root- > left = root- > right; root- > right = temp; return root;}
Dynamically open up and free memory space
As mentioned earlier, the linked list structure allocates storage dynamically, that is, a storage unit of a node is opened up when needed. So, how to dynamically open and release storage units? The library functions of the C language compiler system provide the following related functions.
Malloc function
Void * malloc (unsigned size)
Its function is to allocate a contiguous space of length size in the dynamic storage (heap) of memory, and the return value of this function is a pointer to the starting address of the allocation domain (type void *, that is, null pointer type, which can be converted to other pointer data types when used). If this function fails to execute successfully (for example, when there is insufficient memory space), a null pointer NULL is returned.
Examples of use:
Int * result = malloc (2 * sizeof (int)); struct ListNode * node = malloc (sizeof (struct ListNode))
The above result is an array of length 2 allocated on the heap, which is different from int result [2]; in that the latter is allocated in the memory stack area. Node is a pointer variable to the starting address of data of type struct ListNode (also allocated on the heap).
Calloc function
Void * calloc (unsigned n, unsigned size)
Its function is to allocate n contiguous spaces of length size in the dynamic storage of memory, and the function returns a pointer to the starting address of the allocation domain, or NULL if the allocation is not successful.
Realloc function
Void * realloc (void * p, unsigned size)
Its function is to change the size of the allocated dynamic memory area pointed to by p to size,size that can be larger or smaller than the original allocated space. This function returns a pointer to the starting address of the allocated memory area, or NULL if the allocation is not successful.
If the p passed in is NULL, it has the same effect as the malloc function, which allocates size bytes of memory space.
If the value passed in size is 0, the memory space pointed to by p is freed, but since no new memory space is opened up, a null pointer NULL is returned, similar to calling the free function.
Free function
Void free (void * p)
Its function is to release the memory area pointed to by p, which is generally the value returned by calling the above functions, so that it can be used by other variables. The free function has no return value.
Common body / union
Sometimes we need to store several different types of variables in the same memory unit. For example, you can put an integer variable (2 bytes), a character variable (1 byte), and a real variable (4 bytes) in a memory cell with the same start address, as shown in the following figure:
The above three variables occupy different bytes in memory, but they are all stored at the same address, that is, several variables cover each other. This structure, which allows several different variables to share the same piece of memory, is called a "common body" type, also known as a "union".
Definition of common volume variables
The general form of defining a common body type variable is:
Union shared body name {member list} variable
List; for example:
Union data {int i; char c; float f;} a, b, c
You can also separate the type declaration from the definition of the variable
Union data {int i; char c; float f;}; union data a, b, c
That is, first declare a union data type, and then define a, b, c as the union data type. In addition, you can omit the common body name and define the common body variable directly:
Union {int i; char c; float f;} a, b, c
As you can see, the definitions of "common body" and "structure" are similar, but their meanings are different:
The memory length occupied by structure variables (the total number of bytes) is the sum of the memory length occupied by each member, and each member has its own memory unit.
The memory length occupied by the common volume variable is equal to the length of the longest member. For example, the common body variables a, b, and c defined above account for 4 bytes each (because the longest real variable accounts for 4 bytes), instead of 2 "1", 4 "7 bytes each.
Reference to a common volume variable
Similar to structures, members in common volume variables are referenced as follows:
Share the body variable name. Member name
A common body variable can only be referenced if it is defined first, and it cannot be referenced directly, only members of the common body variable can be referenced. For example, if you defined the common volume variable an earlier, then:
A. I refers to the integer variable I in the common volume variable.
A.C refers to the character variable c in the reference common body variable.
A. F refers to the real variable f in the common volume variable.
But you can't just reference a common body variable, such as printf ("% d", a); is wrong, because there are several types of storage for a, each of which takes up bytes of different lengths, and only the common body variable name an is written, which makes it difficult for the system to determine which member's value is output.
The characteristics of common body type data
When using common body type data, you should pay attention to the following characteristics:
The same memory segment can be used to store several different types of members, but only one of them can be stored at a time, rather than several at the same time. That is to say, only one member works at each moment, and the other members do not work, that is, the members of the common body do not exist and function at the same time.
The member that plays a role in the common body variable is the last stored member, and after saving a new member, the original member loses its function. For example, there is the following assignment statement:
A.I = 1; A.C = 'Franch; a.f = 2.5
After the above three assignment statements are executed, only a.f is valid at this time, while a.i and a.c are meaningless. Therefore, when referencing a member of a common body variable, the programmer himself must know exactly which member is currently stored in the common body variable.
The address of the common variable and the address of its members are the same address, such as & a, & a.i, & a.c, & a.f are all the same address value, and the reason is obvious.
You cannot directly assign a value to a common body variable name, nor can you attempt to reference a variable name to get a value, nor can it be initialized when a common body variable is defined. For example, none of the following is true:
Union {int i; char c; float f;} a = {1, 'averse, 1.5}; / cannot initialize a = 1 for the common body; / / cannot assign m = a to the common body variable; / / cannot refer to the common body variable name to get a value
You cannot use a common body variable as a function parameter, nor can a function return a variable of a community type, but you can use a pointer to a common body variable (similar to the pointer usage of a structure body variable, which is not repeated).
The common body type can appear in the structure type definition, or you can define the common body array. Conversely, structures can also appear in the common body type definition, and arrays can also be used as members of the common body.
This is the end of the article on "how to use structures and Commons in C language". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use the structure and common body in C language". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.