18.C language structure

First, the concept of the structure

Tutorial we explain the foregoing variables and arrays (Array), a is a variable defined, an array is a collection of variables of the same type. But in real life and work, in order to express a set of data, need to use different data types of variables. Super Girl example, basic information, a string name, height and age are integers, floating point numbers weight, size and color value of the string, because of the different data sets each element data type can not be used to store an array.

With knowledge before we learned, if you want to store the information super girl, you can use multiple variables, as follows:

  char name[51];   // 姓名
  int  age;        // 年龄
  int  height;     // 身高,单位:cm
  double weight;     // 体重,单位:kg
  char sc[31];     // 身材,火辣;普通;飞机场
  char yz[31];     // 颜值,漂亮;一般;歪瓜裂枣

This approach has a defect, if a data set has elements 100, 100 is necessary to define the variables, initialization variables 100, 100 to the transfer function of the variable as a parameter, too much trouble.

In the C language, a structure (struct) to store a set of different types of data, the following syntax:

struct 结构体名
{
  结构体成员变量一的声明;
  结构体成员变量二的声明;
  结构体成员变量三的声明;
  ......
  结构体成员变量四的声明;
};

Structure is a collection that is a type of configuration data, the programmer is to describe a data type definition data set out themselves. Members of the structure (Member) may be any type of a variable, a structure may be variable. To Super Girl example:

struct st_girl
{
  char name[51];   // 姓名
  int  age;        // 年龄
  int  height;     // 身高,单位:cm
  int  weight;     // 体重,单位:kg
  char sc[31];     // 身材,火辣;普通;飞机场
  char yz[31];     // 颜值,漂亮;一般;歪瓜裂枣
};

Second, the structure variable

Structure is a programmer-defined data type, a template can use it to define variables. E.g:

struct st_girl queen, princess, waiting, workers;

Structure defines four variables, queen queen, princess Princess, waiting ladies and attendant workers.

Third, the case of memory-intensive

, And each member of the array is very similar in terms of structure theory in memory is stored in a row, however, the total size of the memory for the structure is not necessarily equal to the total size of the memory for member variables and. In a particular realization of the compiler, to improve the efficiency of memory addressing, there may be a gap between various members. Content can be obtained by the structure occupying in the total size sizeof, sizeof (name structure) or
sizeof (variable name structure) may be used.

Example (book90.c)

/*
 * 程序名:book90.c,此程序用于演示C语言的结构体占用内存的情况
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>

struct st_girl
{
  char name[50];     // 姓名
  int  age;          // 年龄
  int  height;       // 身高,单位:厘米cm
  char sc[30];       // 身材,火辣;普通;飞机场。
  char yz[30];       // 颜值,漂亮;一般;歪瓜裂枣。
};

int main()
{
  struct st_girl queen;
  printf("sizeof(struct st_girl) %d\n",sizeof(struct st_girl));
  printf("sizeof(queen) %d\n",sizeof(queen));
}

running result

Here Insert Picture Description

As can be seen from the above example, struct
st_girl memory occupied by all member variables is 50 + 4 + 4 + 30 + 30 = 118, but the structure is occupied by the memory 120.

Note, C language provides a method for memory alignment structure member, you can make the memory structure members are no gaps between the variables, I do not introduced.

Fourth, the variable name structure

And the array is not the same as the address variable name is not a structure variable structure, a structure variable name is the variable name, like int ii same, but can not be directly output, direct output does not make sense. Take & address to use, not a dead end, not directly output on the line.

  struct st_girl stgirl;
  printf("%d\n",stgirl);   // 没有意义。
  printf("%p\n",stgirl);   // 没有意义,结构体变量名不是结构体变量的地址。
  printf("%p\n",&stgirl);  // 这才是结构体的地址。

Fifth, the structure is initialized

Using memset function initializes the structure, the value of all the member variables are cleared.

memset(&queen,0,sizeof(struct st_girl));

or

memset(&queen,0,sizeof(queen));

Note, if the address of a structure passed to subroutine, subroutine with a pointer to a structure (e.g. struct
st_girl
* PST) to store the incoming address of the structure, then, the following method can only Functions to initialize the structure:

memset(pst,0,sizeof(struct st_girl));

The following methods can not be used to initialize the structure:

memset(pst,0,sizeof(pst));

Because the sub-functions with sizeof (pst), the resulting structure is not occupied by the number of bytes of memory, but occupy a structure pointer variable number of bytes of memory (8 bytes).

Six members of the visit (to use)

That use the dot. Operator to access the member (use) of the structure, using the same structure using the common member variables and variables.

Example (book92.c)

/*
 * 程序名:book92.c,此程序演示结构体的访问(使用)。
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <string.h>

struct st_girl
{
  char name[50];     // 姓名
  int  age;          // 年龄
  int  height;       // 身高,单位:厘米cm
  char sc[30];       // 身材,火辣;普通;飞机场。
  char yz[30];       // 颜值,漂亮;一般;歪瓜裂枣。
};

int main()
{
  struct st_girl queen;  // 定义结构体变量
  
  // 初始化结构体变量
  memset(&queen,0,sizeof(struct st_girl));

  // 对结构体每个成员赋值
  strcpy(queen.name,"武则天");
  queen.age=28;
  queen.height=168;
  strcpy(queen.sc,"火辣");
  strcpy(queen.yz,"漂亮");

  printf("姓名:%s\n",queen.name);
  printf("年龄:%d\n",queen.age);
  printf("身高:%d\n",queen.height);
  printf("身材:%s\n",queen.sc);
  printf("颜值:%s\n",queen.yz);
}

running result

Here Insert Picture Description

Seven array of structures

The structure may be defined as an array variable, there is no difference with other types of array variable nature.

struct st_girl princess[6];
memset(princess,0,sizeof(princess));
strcpy(princess[0].name,"杨玉环");
princess[0].age=18;
strcpy(princess[1].name,"西施");
princess[1].age=28;
……

In the actual development, we rarely use the array of structures, vector container C ++ Standard Library is a dynamic array of structures, more convenient than the array of structures.

Eight, a structure pointer

Structure is a self-defined data type, structure variable is a memory variable, there is the memory address, it has a structure pointer.

In pointer chapters we have studied, using different types of data pointer to address variables of different data types, this rule also applies to the structure. as follows:

struct st_girl queen;
struct st_girl *pst=& queen;

It may be used by a structure member structure pointer, the general form:

(*pointer).memberName

or:

pointer->memberName

First writing, the dot. Precedence over *, (* pointer) on both sides of the brackets can not be less. If you remove the brackets writing * pointer.memberName, then it is equivalent to * (pointer.memberName), so the meaning is completely wrong.

In the second writing, -> it is a new operator, used to call it "arrow", with it, may be used directly by the structure member structure pointer; this is the -> C in the only language in use.

The above is equivalent to two way, programmers usually written later, this more intuitive.

Example (book93.c)

/*
 * 程序名:book93.c,此程序演示结构体的指针
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <string.h>

struct st_girl
{
  char name[50];     // 姓名
  int  age;          // 年龄
};

int main()
{
  struct st_girl *pst,queen;  // 定义结构体变量
  
  // 初始化结构体变量
  memset(&queen,0,sizeof(struct st_girl));

  pst=&queen;

  // 对结构体每个成员赋值
  strcpy(pst->name,"武则天");
  pst->age=28;

  printf("姓名:%s,年龄:%d\n",queen.name,queen.age);
  printf("姓名:%s,年龄:%d\n",pst->name,pst->age);
  printf("姓名:%s,年龄:%d\n",(*pst).name,(*pst).age);
}

running result

Here Insert Picture Description

Copy Nine, structure

In the C language, if the members of the structure is the basic data type (int, char, double) = number can be assigned, if a string, the string is not basic data types, which can be given strcpy function, if we want to structure the value of the variable assigned to another structure variables, there are two methods: 1) a is the value of the variable by one member of the structure assigned to a member of another structure variable, this method was awkward, nobody use; 2 ) another method is to memory copy, C language provides the memcpy (memory
copy shorthand) to implement memory copy function.

Function declaration:

void *memcpy(void *dest, const void *src, size_t n);

Parameter Description:

src the starting address of the source of the memory variable.

dest starting address of the destination memory variables.

n number of bytes required to copy the content.

Function returns the address points to the dest, the function returns the value of little significance, programmers generally do not care about the return value.

Example (book94.c)

/*
 * 程序名:book94.c, 此程序演示采用memcpy函数复制结构体
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <string.h>

struct st_girl
{
  char name[50];     // 姓名
  int  age;          // 年龄
};

void main()
{
  struct st_girl girl1,girl2;

  strcpy(girl1.name,"西施");  // 对girl1的成员赋值
  girl1.age=18;

  // 把girl1的内容复制到girl2中
  memcpy(&girl2,&girl1,sizeof(struct st_girl));

  printf("girl1.name=%s,girl1.age=%d\n",girl1.name,girl1.age);
  printf("girl2.name=%s,girl2.age=%d\n",girl2.name,girl2.age);
}

running result

Here Insert Picture Description
You may think strcpy function, and memcpy are similar, in fact, these two functions from the function and implement the principles of finishing this different, should not even put them together.

1) different copied content, only copy the string strcpy, memcpy and can copy the contents of any such character array, integers, structures, and the like.

2) different uses, usually strcpy when copying a string, while other types of data need to be copied when used is generally memcpy

Different 3) method of copying, strcpy need not specify the length, it encounters a character string to be copied until the end closings 0, memcpy is depending on its third parameter determines the length of replication.

X. structure as a parameter

Structure is a set of a plurality of variables, when the entire set can be passed as parameters, i.e. all members. If structure members are more initialization and assignment of function parameters memory overhead may be significant, affecting the efficiency of the program. So the best way is to pass the address of the structure variable.

Example (book95.c)

/*
 * 程序名:book95.c,此程序演示结构体作为函数的参数。
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <string.h>

struct st_girl
{
  char name[50];     // 姓名
  int  age;          // 年龄
};

// 对结构体赋值的函数
void setvalue(struct st_girl *pst);

int main()
{
  struct st_girl queen;  // 定义结构体变量
  
  // 初始化结构体变量
  memset(&queen,0,sizeof(struct st_girl));

  setvalue(&queen);  // 调用函数,传结构体的地址

  printf("姓名:%s,年龄:%d\n",queen.name,queen.age);
}

void setvalue(struct st_girl *pst)
{
  // 对结构体每个成员赋值
  strcpy(pst->name,"武则天");
  pst->age=28;
}

running result

Here Insert Picture Description

XI, enumeration and Community

There are also two C language data structures: enumeration and Community, the application of the two data structures too little, as little as I can not remember their definitions, twenty years, I've never used, nor introduced .

Twelve, memset function and bzero

1, memset function

memset function is a function of the assignment of memory space, the memory space used to carry out a certain assignment.

Included in the < string.h > header file.

Function declaration as follows:

void *memset(void *s, int v, size_t n);  

s memory space address, the name or address of the array is generally structured body.

v is the value to be filled, fill 0 is initialized.

n is the number of bytes to be filled.

In the actual development, programmers array or structure cleared memset function in the previous section, we have used many times.

2, bzero function

bzero function is a memory space cleared.

Included in the < string.h > header file.

Function declaration as follows:

void bzero(void *s, size_t n); 

s memory space address, the name or address of the array is generally structured body.

n is the number of bytes to be zeroed.

If you want to clear the array or structure, using memset and bzero can be, no difference, see the programmer habits.

XIII homework

Write the sample program, this section describes the knowledge of all the demo again, the demo program can deepen your understanding and mapping.

XIV copyright notice

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.
Source: C Language Technology Network (www.freecplus.net)
Author: Ethics code Agriculture

If the article typos, or content errors, or other suggestions and comments, please correct me message, thank you very much! ! !

Published 29 original articles · won praise 2 · Views 677

Guess you like

Origin blog.csdn.net/m0_45133894/article/details/104647823