English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about structure types in C language programming. You will learn to define and use structures with examples.
In C language programming, sometimes it is necessary to store multiple properties of entities. Entities do not have to have all information of only one type. They can have different properties of different data types.
C arrays allow you to define variables that can store items of the same type.Structureis another user-defined data type available in C programming that allows you to store different data items.
Structures are used to represent a record, assuming you want to track the dynamics of books in a library, you may need to track the following properties of each book:
Title
Author
Subject
Book ID
To define a structure, you must use struct keyword. The struct statement defines a new data type containing multiple members, and the format of the struct statement is as follows:
struct tag { member-list member-list member-list ... } variable-list ;
tag is a structure tag.
member-list is a standard variable definition, such as int i; or float f, or any other valid variable definition.
variable-list Structure variables, defined at the end of the structure, before the last semicolon, allow you to specify one or more structure variables. Here is the way to declare the Book structure:
struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book;
In general,tag, member-list, variable-list This 3 Parts must appear at least 2 members. The following is an example:
//This declaration declares a structure with3members, respectively an integer a, a character b, and a double-precision c //and also declares a structure variable s1 //This structure does not specify its label struct { int a; char b; double c; } s1; //This declaration declares a structure with3members, respectively an integer a, a character b, and a double-precision c //The label of the structure is named SIMPLE, and no variable is declared struct SIMPLE { int a; char b; double c; }; //A structure declared with the SIMPLE tag, and another variable t is declared1, t2, t3 struct SIMPLE t1, t2[20], *t3; //You can also use typedef to create a new type typedef struct { int a; char b; double c; } Simple2; //Now you can use Simple2As a type declaration for a new structure variable Simple2 u1, u2[20], *u3;
In the above declaration, the first and second declarations are treated as two completely different types by the compiler, even though their member lists are the same, if you let t3&s1, is illegal.
The members of a structure can include other structures, or pointers to its own structure type, and this pointer is usually used to implement more advanced data structures such as lists and trees.
//This structure declaration includes other structures struct COMPLEX { char string[100]; struct SIMPLE a; }; //This structure declaration includes a pointer to its own type struct NODE { char string[100]; struct NODE *next_node; };
If two structures contain each other, an incomplete declaration must be made for one of the structures, as shown below:
struct B; //Incomplete declaration of structure B //Structure A contains a pointer to structure B struct A { struct B *partner; //other members; }; //Structure B contains a pointer to structure A, and B is also declared after A is declared. struct B { struct A *partner; //other members; };
Like other types of variables, the initial value can be specified when defining a structure variable.
#include <stdio.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book = {"C Language", "w3codebox", "Programming Language", 123456}; int main(); { printf("Book name: %s\nAuthor: %s\nSubject: %s\nBookID %d\n", book.title, book.author, book.subject, book.book_id); }
The execution output is as follows:
Title: C Language Author: w3codebox Subject: Programming Language BookID 123456
To access the members of the structure, we usemember access operator (.). member access operator is a period between the structure variable name and the structure member we want to access. You can use struct Keywords to define variables of structure types. The following example demonstrates the usage of structures:
#include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { struct Books Book1; /* Declare Book1, type of Books */ struct Books Book2; /* Declare Book2, type of Books */ /* Book1 Elaborate */ strcpy(Book1.title, "C Programming Language"); strcpy(Book1.author, "Nuha Ali"); strcpy(Book1.subject, "C Programming Language Tutorial"); Book1.book_id = 6495407; /* Book2 Elaborate */ strcpy(Book2.title, "JAVA Programming Language"); strcpy(Book2.author, "Seagull Ali"); strcpy(Book2.subject, "JAVA Programming Language Tutorial"); Book2.book_id = 6495700; /* Output Book1 information */ printf("Book 1 Title: %s\n", Book1.title); printf("Book 1 Author: %s\n", Book1.author); printf("Book 1 Subject: %s\n", Book1.subject); printf("Book 1 ID: %d\n", Book1.book_id); /* Output Book2 information */ printf("Book 2 Title: %s\n", Book2.title); printf("Book 2 Author: %s\n", Book2.author); printf("Book 2 Subject: %s\n", Book2.subject); printf("Book 2 ID: %d\n", Book2.book_id); return 0; }
When the above code is compiled and executed, it will produce the following result:
Book 1 Title: C Programming Language Book 1 Author: Nuha Ali Book 1 Subject: C Programming Language Tutorial Book 1 ID: 6495407 Book 2 Title: JAVA Programming Language Book 2 Author: Seagull Ali Book 2 Subject: JAVA Programming Language Tutorial Book 2 ID: 6495700
You can pass a structure as a function parameter in the same way as other types of variables or pointers. You can access the structure variable in the same way as shown in the example above:
#include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; /* Function declaration */ void printBook(struct Books book); int main() { struct Books Book1; /* Declare Book1, type of Books */ struct Books Book2; /* Declare Book2, type of Books */ /* Book1 Elaborate */ strcpy(Book1.title, "C Programming Language"); strcpy(Book1.author, "Nuha Ali"); strcpy(Book1.subject, "C Programming Language Tutorial"); Book1.book_id = 6495407; /* Book2 Elaborate */ strcpy(Book2.title, "JAVA Programming Language"); strcpy(Book2.author, "Seagull Ali"); strcpy(Book2.subject, "JAVA Programming Language Tutorial"); Book2.book_id = 6495700; /* Output Book1 information */ printBook(Book1 ); /* Output Book2 information */ printBook(Book2 ); return 0; } void printBook(struct Books book) { printf("Book Title: %s\n", book.title); printf("Book Author: %s\n", book.author); printf("Book Subject: %s\n", book.subject); printf("Book ID: %d\n", book.book_id); }
When the above code is compiled and executed, it will produce the following result:
Book Title: C Programming Language Book Author: Nuha Ali Book Topic: C Programming Language Tutorial Book Number: 6495407 Book Title: JAVA Programming Language Book Author: Seagull Ali Book Topic: JAVA Programming Language Tutorial Book Number: 6495700
You can define a pointer to a structure in a way similar to defining a pointer to other types of variables, as shown below:
struct Books *struct_pointer;
Now, you can store the address of the structure variable in the pointer variable defined above. To find the address of the structure variable, place the & operator in front of the structure name, as shown below:
struct_pointer = &Book1;
To access the structure members using a pointer to the structure, you must use -operator, as shown below:
struct_pointer-title;
Let us rewrite the above example using a structure pointer, which will help you understand the concept of structure pointers:
#include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; /* Function declaration */ void printBook(struct Books *book); int main() { struct Books Book1; /* Declare Book1, type of Books */ struct Books Book2; /* Declare Book2, type of Books */ /* Book1 Elaborate */ strcpy(Book1.title, "C Programming Language"); strcpy(Book1.author, "Nuha Ali"); strcpy(Book1.subject, "C Programming Language Tutorial"); Book1.book_id = 6495407; /* Book2 Elaborate */ strcpy(Book2.title, "JAVA Programming Language"); strcpy(Book2.author, "Seagull Ali"); strcpy(Book2.subject, "JAVA Programming Language Tutorial"); Book2.book_id = 6495700; /* by passing Book1 of the address to output Book1 information */ printBook(&Book1 ); /* by passing Book2 of the address to output Book2 information */ printBook(&Book2 ); return 0; } void printBook(struct Books *book) { printf("Book Title: %s\n", book->title); printf("Book Author: %s\n", book->author); printf("Book Topic: %s\n", book->subject); printf("Book Number: %d\n", book->book_id); }
When the above code is compiled and executed, it will produce the following result:
Book Title: C Programming Language Book Author: Nuha Ali Book Topic: C Programming Language Tutorial Book Number: 6495407 Book Title: JAVA Programming Language Book Author: Seagull Ali Book Topic: JAVA Programming Language Tutorial Book Number: 6495700
Some information does not need to occupy a complete byte when stored, but only a few or one binary bit. For example, when storing a switch variable, only 0 and 1 Two states, using 1 The bit binary bit can be used. To save storage space and make processing simpler, the C language also provides a data structure called 'bit field' or 'bit segment'.
The so-called 'bit field' is to divide the binary bits of a byte into several different areas and specify the number of bits for each area. Each field has a field name, which allows operations by field name in the program. In this way, several different objects can be represented by a binary bit field of a byte.
Typical example:
Use 1 When a bit binary stores a switch variable, only 0 and 1 Two states.
Read external file format - can read non-standard file formats. For example:9 Integer bits.
The definition of bit fields is similar to the definition of structures, and its form is:
struct bit field structure name { Bit field list };
The form of the bit field list is:
Type specifier bit field name: bit field length
For example:
struct bs{ int a:8; int b:2; int c:6; } data;
The description of data is the bs variable, a total of two bytes. Among them, the bit field a occupies 8 Bit, bit field b occupies 2 Bit, bit field c occupies 6 Bit.
Let's look at another example:
struct packed_struct { unsigned int f1:1; unsigned int f2:1; unsigned int f3:1; unsigned int f4:1; unsigned int type:4; unsigned int my_int:9; } pack;
In this case, packed_struct contains 6 A member: four 1 Bits identifier f1..f4, one 4 Bits type and one 9 Bits my_int.
The following are some explanations for the definition of bit fields:
A bit field is stored in the same byte, such as when the remaining space in a byte is not enough to store another bit field, it will start storing the bit field from the next unit. It can also be intentionally made for a bit field to start from the next unit. For example:
struct bs{ unsigned a:4; unsigned :4; /* Empty space */ unsigned b:4; /* Start storing from the next unit */ unsigned c:4 }
In this bit field definition, a occupies the first byte of 4 Bit, after 4 Bit fill 0 means not used, b starts from the second byte and occupies 4 Bit, c occupies 4 Bit.
Since bit fields do not allow crossing two bytes, the length of bit fields cannot be greater than the length of a word, that is, it cannot exceed8Bit binary. If the maximum length is greater than the length of the integer of the computer, some compilers may allow the memory overlap of the fields, and some compilers may store the part greater than one field in the next word.
Bit fields can be anonymous bit fields, in which case they are only used for padding or adjusting position. Anonymous bit fields cannot be used. For example:
struct k{ int a:1; int :2; /* The 2 Bits cannot be used */ int b:3; int c:2; };
From the above analysis, it can be seen that bit fields are essentially a structure type, but their members are allocated by binary bits.
The usage of bit fields is the same as that of structure members, and its general form is:
Bit field variable name.bit field name Bit field variable name->Bit field name
Bit fields can be output in various formats.
Please see the following example:
main(){ struct bs{ unsigned a:1; unsigned b:3; unsigned c:4; } bit,*pbit; bit.a=1; /* Assign values to bit fields (note that the assignment cannot exceed the allowed range of the bit field) */ bit.b=7; /* Assign values to bit fields (note that the assignment cannot exceed the allowed range of the bit field) */ bit.c=15; /* Assign values to bit fields (note that the assignment cannot exceed the allowed range of the bit field) */ printf("%d,%d,%d\n",bit.a,bit.b,bit.c); /* Output the content of the three fields in integer format */ pbit=&bit; /* Send the address of the bit field variable bit to the pointer variable pbit */ pbit->a=0; /* Assign a new value of 0 to the bit field a */ pbit->b&=3; /* The compound bitwise operator "&=" is used, which is equivalent to: pbit->b=pbit->b&3,the original value of the bit field b is 7,与 3 The result of the bitwise AND operation is 3(111&011=011The decimal value is 3) */ pbit->c|=1; /* The compound bitwise operator "|=" is used, which is equivalent to: pbit->c=pbit->c|1The result is 15 */ printf("%d,%d,%d\n",pbit->a,pbit->b,pbit->c); /* The values of these three fields are output using pointers */ }
In the above example program, the bit field structure bs is defined, with three bit fields a, b, c. It demonstrates the variables of type bs and a pointer variable pointing to the bs type. This indicates that bit fields can also be used with pointers.
We use the typedef keyword to create aliases for data types. It is usually used with structures to simplify the syntax of variable declarations.
This code
struct Distance{ int feet; float inch; }; int main() { struct Distance d1, d2; }
Is equivalent to
typedef struct Distance{ int feet; float inch; } distances; int main() { distances d1, d2; }
You can create structures within structures in C programming. For example,
struct complex { int imag; float real; }; struct number { struct complex comp; int integers; } num1, num2;
Suppose, you want to set num2The variable imag's value is11How to do it? See the following example:
num2.comp.imag = 11;
Suppose you want to store information about a person: he/Her name, ID number and salary. You can create different variables name, citNo and salary to store this information.
What if you need to store information for multiple people? Now, you need to create different variables for each piece of information for each person: name1, citNo1, salary1, name2, citNo2, salary2, etc.
A better way is to collect all relevant information under a single name, the Person structure, and use it for each person.