C language data type (2) - constructing a data type

As mentioned in the previous article, there are three types of C language data types: basic data types, constructed data types, and pointer types.
The basic data types have been described above, and this article introduces the construction of data types. Constructed data types are further divided into three types: array type, structure type, union type, and enumeration type.
insert image description here

array type

First of all, we need to clarify a question, why do we have an array?
For example: Now it is necessary to count the grades of 10 students. If the basic data type is used to define at least 10 variables to store these data, if there are 100 students, at least 100 variables are required.

float a0,a1,a2,a3,a4,a5,a6,a7,a8,a9;

When using basic data types to define variables, if there are many variables of the same type, it will be more troublesome to define. If you use arrays to solve the above problems, it will be very convenient,

float a[10];

Only one statement is needed to realize the definition of multiple variables of the same type. In contrast, the advantages of arrays are highlighted, which is why we need arrays. With this practical problem, it is easier for us to understand the concept of an array-a collection of data of the same type.
Arrays and array elements : An array is a collection of data of the same type represented by a name, and this name is called the array name. The data in the array is stored in variables distinguished by subscripts, and these variables are called subscript variables or array elements. Each subscript variable is equivalent to a simple variable, and the type of the array is also the data type of the subscript variable of the array. The array belongs to the structure type, and the data of the structure type is composed of the basic type data according to certain rules.
Arrays used in C language include one-dimensional arrays and multidimensional arrays.

one-dimensional array

One-dimensional array definition

Definition form:
data type array name [constant expression];

"Data Type": is the data type of the array elements.
"Array name": follow the C language identifier rules.
"Constant expression": Indicates how many elements are in the array, that is, the length of the array. It can be an integer constant, an integer constant expression, or a symbolic constant.

int a[5];

A one-dimensional array a is defined, int means that each element in a in the array is an integer, the array name is a, and this array has 5 elements. The array subscript starts from 0, so the 6 elements of the a array defined above are a[0], a[1], a[2], a[3], a[4], which are stored continuously in memory, and the array The first address of the array is the address of a[0], and the array name represents the first address of the array (the address is very important and will be used in the pointer), that is, the value of a and the address value of a[0] (&a[0] )Same.

1D array reference

Reference form:
array name [subscript expression];

Among them, "subscript expression": it can only be an integer constant or an integer expression.
Note : The subscript starts from 0 (the lower bound is 0), and the maximum subscript (upper bound) of the array is the length of the array minus 1.

	int a[10];
	a[0]=0;
	scanf("%d",&a[10]);/*下标越界*/

The third line of the above code is incorrectly used, the array subscript can only reach (n-1) digits, and n is the number of array elements.

One-dimensional array initialization

1. When defining an array. Initialize all array elements

int a[5]={
    
    0,1,2,3,4};

The value of a[0] is 0, the value of a[1] is 1,..., the value of a[4] is 4.
When assigning initial values ​​to all array elements, the length of the array can be specified differently, such as:

int a[]={
    
    0,1,2,3,4};

The system defines the length of the a array as 5 according to the number of initial values.
2. When defining an array, assign initial values ​​to some array elements

int a[5]={
    
    0,1,2};

The value of a[0] is 0, the value of a[1] is 1, the value of a[2] is 2, and the rest of the elements are 0.

Two-dimensional array

Two-dimensional array definition

Definition form:
data type array name [constant expression 1] [constant expression 2];

[Constant expression 1] indicates the number of rows of the two-dimensional array, and [Constant expression 2] indicates the number of columns of the two-dimensional array.

float x[2][3];

Define x as an array of 2 rows and 3 columns, with a total of six elements, and each element is of float type. The system allocates a continuous storage space in the memory for the two-dimensional array, and the arrangement order of the elements is stored in rows, that is, x[0][0], x[0][1], x[0][2] , x[1][0], x[1][1], x[1][2]. The array name represents the first address of the array.
A two-dimensional array can be seen as a special kind of one-dimensional array, and the x array can be regarded as a one-dimensional array containing two large elements, and each element is a one-dimensional array containing three elements.
x[0]------x[0][0], x[0][1], x[0][2]
x[1]------x[1][0] , x[1][1], x[1][2]
x[0] is the first address of the first line of the two-dimensional array, that is, the address of x[0][0], and x[1] is the two-dimensional array The first address of the second line, that is, the address of x[1][0].

reference to a two-dimensional array

Reference form:
array name [row subscript expression] [column subscript expression]
Note : the row and column subscripts of a two-dimensional array start from 0 (the lower bound is 0)

int a[3][4];
a[0][0]=3;
a[0][1]=a[0][0]+10;	

Error reference:

a[3][4]=3;/*下标越界*/
a[1,2]=1;/*应写成a[1][2]=1;*/

Two-dimensional array initialization

1. Assign initial value by row:

int a[2][3]={
    
    {
    
    1,2,3},{
    
    4,5,6}};

Initialization result:
first line: 1 2 3
second line: 4 5 6
2. Assign initial values ​​to each element according to the order in which the array elements are arranged in memory:

int a[2][3]={
    
    1,2,3,4,5,6};

Initialization result:
first line: 1 2 3
second line: 4 5 6
3. Assign initial values ​​to some elements:

int a[2][3]={
    
    {
    
    1},{
    
    4}};

Initialization result:
first line: 1 0 0
second line: 4 0 0

Special Note - Character Arrays

Similar to the previous integer arrays and real arrays, character arrays are also a type of array. Then why should the character array be raised separately? It is different from other types of arrays. If it is an integer array, it stores integer data. If it is a real array, it stores real data. But character arrays can store both character data and strings, and strings can only be stored in character arrays , which is its special feature.

string

To figure out whether the character data stored in the character array is still a string, the first thing to figure out is the difference between a character and a string. The difference between a character and a string is whether there is a string end mark ('\0'). If there is a string end flag, it is a string, otherwise it is a character.

char a[5]={
    
    'C','h', 'i', 'n', 'a' };
char b[6]={
    
    'C','h', 'i', 'n', 'a' , '\0'};

As shown in the above two lines of code, there is no string end mark ('\0') in the a array, so the characters stored in the a array are 'C', 'h', 'i', 'n', 'a'; and '\0' is contained in the b array, and the string China is stored in the b array.

Initialization of character arrays

1. Use character constants to assign initial values

char a[5]={
    
    'C','h', 'i', 'n', 'a' };

The a array stores 5 character data, not strings, and each array element and subscript correspond to an integer array.

char b[6]={
    
    'C','h', 'i', 'n', 'a' , '\0'};

Because b[5]='\0' in the b array, the strings are stored in the b array.

2. Assign the initial value with a string constant

char str[10]= {
    
    "a string"};
char str[10]= "a string";

The above two lines of code have the same function, and both store a string (a string) in the str array.

char a[3][10]={
    
    "basic","pascal","c"};

The a array has three rows, and each row stores a string.
This also shows that if the length of the array is greater than the length of the assigned content, the system will automatically fill in '\0' in the remaining position, and the content stored in the array will become a string. like:

char s3[7]={
    
     's', 't', 'r', 'i', 'n', 'g'};

The length of the character array is 7 digits, but the user only assigns 6 digits when assigning a value, then the system will automatically fill the seventh digit with '\0', that is, s3[7]='\0'

3. Omission of length during initialization

char s1[ ]= "Good morning!";

At this time, the length of the s1 array is 14, and s1[13]='\0'. A string is stored in the s1 array.

char s2[ ]={
    
     's', 't', 'r', 'i', 'n', 'g'};

At this time, the length of the s2 array is 6. There is no end-of-string marker in the array. Therefore it cannot be used as a string.

reference to character array

References to character arrays can be divided into references to individual elements of the character array and references to the entire character array. References to individual elements of character arrays are the same as for integer and real arrays. The overall reference to the character array is mainly manifested on the input and output.

char c[ ]= "China";
printf("%s",c);

Where c is the name of the array, representing the first address of the array. The output is China.

char c[10];
scanf("%s",c)

If the input is Beijing, the string "Beijing" is stored in the array.

array summary

An array is a collection representing a set of data of the same type, and is used when many variables of the same type are required. Divided into one-dimensional arrays and multidimensional arrays.
The first thing to note is that the subscript of the array cannot cross the boundary. The subscript of the array starts from 0, and the subscript cannot cross the boundary when defining or quoting. This is a mistake that is often made.
The second point is the address of the array. The address is very important in the subsequent pointer reference. It is necessary to clarify that the array name represents the first address of the array and what is the first address of each row of the two-dimensional array. How the addresses of the elements of the array are allocated in the computer is helpful for subsequent learning of pointers.

Structure type

The array type is very convenient and flexible for large-scale data processing, but it also has certain restrictions, that is, the elements of the same array must all be of the same type of data. Is there a data type that can bring together various data types? Then there are structures and unions.
A structure is composed of several data items, and each data item that makes up a structure is called a structure member. The data types of each member in the structure can be different. Before using structure type data, the structure type must be defined first. The general form of a structure definition:

struct 结构体名
{
    
    数据类型1 成员名1;
 数据类型2 成员名2...
 数据类型n 成员名n;
};

Among them, struct is a keyword of C language, which indicates the definition of structure type. The final semicolon marks the end of the struct type definition. Structure members can be of any data type allowed by the C language. For example:

struct bookcard
{
    
    char num[10];
 char mane[30];
 char author[30];
 char publisher[60];
 float price;
 int n;
};

Note: The definition of the structure type only shows the composition of the type, the system does not allocate memory space for it, and the compilation system only allocates memory space for variables, so the space occupied by the structure is equal to the space occupied by each structure member . and . The type of a struct member can also be another struct type.

Definition of structure type variable

1. Use the defined structure type to define variables
This method should be used when multiple functions in a program need to define variables of the same structure type, and the structure type should be defined as a global type, in the form of
struct structure name variable Famous watch;

struct student
{
    
    char num[8];name[20];sex;
 int age;
 float score;
};
void main()
{
    
    struct student a;
...
}
f1()
{
    
    struct student b;
...
}

Since the struct student type is defined outside the function, it is a global variable, so it can be used to define structure variables a and b in the main function and f1 function.
2. Define variables while defining the structure type
This method is generally used to define external variables, and this structure type name can also be used to define local variables in each function. The form is:
struct structure name
{member definition table;
}variable name table;

struct student
{
    
    char num[8];name[20];sex;
 int age;
 float score;
}st[30];
void main()
{
    
    struct student s;
...
}
f1()
{
    
    struct student x;
...
}

A single struct student type variable can only describe the information of one student, and if it is necessary to save the information of 30 students, a structure type array can be defined. As shown above, an external structure array is defined while defining the global type name, and the definition method is the same as other types of array definitions. Each element in this array is a structure type variable. The combined use of these two construct types makes it more general for data processing.

3. Directly define structure type variable
This method can be used when there is only one place in the program that needs a certain structure type variable. In this method, the structure type name is not specified, and the form is:
struct
{member definition table;
}variable name table;

void main()
{
    
    struct
 {
    
    char num[8],name[30],sex;
  int age;
  float score;
 }st[30],a,b,c;
 int i,j;
 ...
}

Initialization of structure variables

When defining a structure variable, you can also assign initial values ​​to its members. The initial value table is enclosed by "{}", and the data in the table are separated by commas, and the number of members should be the same as that of the structure type definition, and the type should be the same. If the number of initial values ​​is less than the number of members of the structure, the members without initial values ​​are assigned a value of 0. If the number of initial values ​​exceeds the number of structure members, a compile error occurs.
Example: Structure variable initialization:

struct date
{
    
    int year,month,day;};
struct student
{
    
    char num[8],name[30],sex;
 struct date birthday;
 float score;
}a={
    
    "40826011","Li ming","M",{
    
    1991,2,9},87.5},
 b={
    
    "40826025","Zhang qiang","F",{
    
    1990,5,12},85},c,d;

Initialization of an array of structures:

struct s
{
    
    char num[8],name[30],sex;
 float score;
}stu[3]={
    
    
		{
    
    "40826011","Li ming","M",87.5},
		{
    
    "40826025","Zhang qiang","F",85},
		{
    
    "40826032","Wang xinping","F",90}
		};

Reference forms of structure variable members

The general form of referencing structure variable members is:
structure variable name. member name
where "." is a component operator with the highest level of operation. For example, in the first piece of code in the structure variable initialization, the members of a can be expressed as a.num, a.name, a.sex, a.birthday and a.score. a, b, c, and d are variables of the same type, and a.num, b.num, c.num, and d.num can be used to distinguish the respective members of the same name num.
Structure pointer: struct student *p;
For example:

struct code
{
    
    int n;
 char c;
}a,*p=&a;

p is a structure pointer pointing to a, and there are 3 ways to refer to the members of variable a:
1.an, ac select members through component operation of variable names;
2.(*p).n,(*p).c : Use the pointer variable indirect storage operator to access the target variable;
3.p->n,p->c: This is a form specially used for structure pointer variables to refer to structure members, which is equivalent to the second form .

Union type

A union is similar to a construction type that shares storage structures of different data types, that is, all members of a union variable will occupy the same storage space. This also shows that the space occupied by the union is equal to the maximum space occupied by its members . The advantage of using this type of data is to save storage space.
The general form of a union type definition is:

union 共用体名
{
    
    数据类型1 成员名1;
 数据类型2 成员名2...
 数据类型n 成员名n;
 }

Among them, union is a keyword of C language, which indicates the definition of union type. The final semicolon marks the end of the union type definition. Union members can be any data type allowed by the C language. For example:

union utype
{
    
    int i;
 char ch;
 long l;
 char c[4];
};

Definition of a union variable

The definition form of union type variable is similar to structure variable definition.
1. union union body name variable name table;
2. union union body name
{member definition table;
} variable name table;

3. union
{member definition table;
} variable name table;

References to members of union variables

As with the structure variable type, there are also 3 forms of references to members of the union

union u
{
    
    char u1;
 int u2;
}x,*p=&x;

The reference form is:
1.x.u1,x.u2;
2.(*p).u1,(*p).u2;
3.p->u1,p->u2;

Guess you like

Origin blog.csdn.net/Tao_9/article/details/129711370