Cprogramming 简明教程

Array of Structures in C

在 C 编程中, struct 关键词用于定义一个派生数据类型。在定义之后,可以声明一个结构变量数组,就像声明 intfloatchar 类型数组那样。一个结构数组有很多使用案例,例如在存储类似于数据库表中的记录时,其中每行都有不同的数据类型。

In C programming, the struct keyword is used to define a derived data type. Once defined, you can declare an array of struct variables, just like an array of int, float or char types is declared. An array of structures has a number of use-cases such as in storing records similar to a database table where you have each row with different data types.

通常,一个结构类型在代码的开头定义,这样其类型可以在任何函数中使用。可以声明一个结构数组,然后在其中填充数据,也可以在声明时初始化数据。

Usually, a struct type is defined at the beginning of the code so that its type can be used inside any of the functions. You can declare an array of structures and later on fill data in it or you can initialize it at the time of declaration itself.

Initializing a Struct Array

让我们定义一个名为 book 的结构类型,如下所示 −

Let us define a struct type called book as follows −

struct book{
   char title[10];
   double price;
   int pages;
};

在程序中,可以通过用花括号给出每个元素的值来声明一个数组并对其进行初始化。结构数组中的每个元素本身都是一个结构值。所以,我们有嵌套的花括号,如下图所示 −

During the program, you can declare an array and initialize it by giving the values of each element inside curly brackets. Each element in the struct array is a struct value itself. Hence, we have the nested curly brackets as shown below −

struct book b[3] = {
   {"Learn C", 650.50, 325},
   {"C Pointers", 175, 225},
   {"C Pearls", 250, 250}
};

How does the compiler allocate memory for this array? 由于我们有一个 struct 的三个元素数组,它的尺寸是 32 字节,数组占用了“32 x 3”字节。每个 32 字节的块将容纳一个“标题”、“价格”和“页数”元素。

How does the compiler allocate memory for this array? Since we have an array of three elements, of struct whose size is 32 bytes, the array occupies "32 x 3" bytes. Each block of 32 bytes will accommodate a "title", "price" and "pages" element.

L

E

A

R

N

C

675.50

325

C

P

O

I

N

T

E

R

S

175

225

C

P

E

A

R

L

S

250

250

Declaring a Struct Array

还可以声明一个空结构数组。之后,可以使用 scanf() 语句读取其中的数据,或按如下所示为每个元素赋予值 −

You can also declare an empty struct array. Afterwards, you can either read the data in it with scanf() statements or assign value to each element as shown below −

struct book b[3];
strcpy(b[0].title, "Learn C");
b[0].price = 650.50;
b[0].pages=325;

strcpy(b[1].title, "C Pointers");
b[1].price = 175;
b[1].pages=225;

strcpy(b[2].title, "C Pearls");
b[2].price = 250;250
b[2].pages=325;

Reading a Struct Array

还可以接受来自用户的输入来填充数组。

We can also accept data from the user to fill the array.

Example 1

在下面的代码中,一个 for 循环用来接受该数组的每个结构元素的“标题”、“价格”和“页数”元素的输入。

In the following code, a for loop is used to accept inputs for the "title", "price" and "pages" elements of each struct element of the array.

#include <stdio.h>

struct book{
   char title[10];
   double price;
   int pages;
};

int main(){

   struct book b[3];

   strcpy(b[0].title, "Learn C");
   b[0].price = 650.50;
   b[0].pages = 325;

   strcpy(b[1].title, "C Pointers");
   b[1].price = 175;
   b[1].pages = 225;

   strcpy(b[2].title, "C Pearls");
   b[2].price = 250;
   b[2].pages = 325;

   printf("\nList of Books:\n");
   for (int i = 0; i < 3; i++){
      printf("Title: %s \tPrice: %7.2lf \tPages: %d\n", b[i].title, b[i].price, b[i].pages);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

List of Books:
Title: Learn C    Price: 650.50 Pages: 325
Title: C Pointers Price: 175.00 Pages: 225
Title: C Pearls   Price: 250.00 Pages: 325

Example 2

在此示例中,定义了一个名为 student 的结构类型。它的元素是“姓名”;物理、化学和数学的成绩;以及“百分比”。

In this example, a struct type called student is defined. Its elements are "name"; marks in physics, chemistry and maths; and the "percentage".

声明了一个由三个学生结构类型组成的数组,并通过一个 for 循环由用户输入填充前四个元素。在循环内部,计算每个下标的“百分比”元素。

An array of three struct student types is declared and the first four elements are populated by user input, with a for loop. Inside the loop itself, the "percent" element of each subscript is computed.

最后,打印一个带有姓名、成绩和百分比的学生数组来显示成绩单。

Finally, an array of students with their names, marks and percentage is printed to show the marklist.

#include <stdio.h>

struct student{
   char name[10];
   int physics, chemistry, maths;
   double percent;
};

int main(){

   struct student s[3];

   strcpy(s[0].name, "Ravi");
   s[0].physics = 50;
   s[0].chemistry = 60;
   s[0].maths = 70;

   strcpy(s[1].name, "Kiran");
   s[1].physics = 55;
   s[1].chemistry = 66;
   s[1].maths = 77;

   strcpy(s[2].name, "Anil");
   s[2].physics = 45;
   s[2].chemistry = 55;
   s[2].maths = 65;

   for (int i = 0; i < 3; i++){
      s[i].percent = (double)(s[i].physics + s[i].maths + s[i].chemistry)/3;
   }

   printf("\nName\tPhysics\tChemistry\t\Maths\tPercent\n");

   for(int i = 0; i < 3; i++){
      printf("%s \t\t%d \t\t%d \t\t%d \t\t%5.2lf\n", s[i].name, s[i].physics, s[i].chemistry, s[i].maths, s[i].percent);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Name  Physics Chemistry Maths Percent
Ravi  50      60        70    60.00
Kiran 55      66        77    66.00
Anil  45      55        65    55.00

Sorting a Struct Array

我们再举一个结构数组的示例。我们将在实现冒泡排序技术之后按价格升序对“book”结构类型数组进行排序。

Let us take another example of struct array. Here, we will have the array of "book" struct type sorted in ascending order of the price by implementing bubble sort technique.

Note : 一个结构变量的元素可以直接通过赋值运算符赋值给另一个结构变量。

Note: The elements of one struct variable can be directly assigned to another struct variable by using the assignment operator.

Example

看一看这个示例 −

Take a look at the example −

#include <stdio.h>

struct book{
   char title[15];
   double price;
   int pages;
};

int main(){

   struct book b[3] = {
      {"Learn C", 650.50, 325},
      {"C Pointers", 175, 225},
      {"C Pearls", 250, 250}
   };

   int i, j;
   struct book temp;

   for(i = 0; i < 2; i++){
      for(j = i; j < 3; j++){
         if (b[i].price > b[j].price){
            temp = b[i];
            b[i] = b[j];
            b[j] = temp;
         }
      }
   }

   printf("\nList of Books in Ascending Order of Price:\n");

   for (i = 0; i < 3; i++){
      printf("Title: %s \tPrice: %7.2lf \tPages: %d\n", b[i].title, b[i].price, b[i].pages);
   }

   return 0;

}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

List of Books in Ascending Order of Price:
Title: C Pointers Price: 175.00 Pages: 225
Title: C Pearls   Price: 250.00 Pages: 250
Title: Learn C    Price: 650.50 Pages: 325

Declaring a Pointer to a Struct Array

还可以声明一个指向结构数组的指针。C 使用间接运算符 (→) 来访问结构变量的内部元素。

We can also declare a pointer to a struct array. C uses the indirection operator (→) to access the internal elements of struct variables.

Example

以下示例演示如何声明指向结构数组的指针 −

The following example shows how you can declare a pointer to a struct array −

#include <stdio.h>

struct book {
   char title[15];
   double price;
   int pages;
};

int main(){

   struct book b[3] = {
      {"Learn C", 650.50, 325},
      {"C Pointers", 175, 225},
      {"C Pearls", 250, 250}
   };

   struct book *ptr = b;

   for(int i = 0; i < 3; i++){
      printf("Title: %s \tPrice: %7.2lf \tPages: %d\n", ptr -> title, ptr -> price, ptr -> pages);
      ptr++;
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Title: Learn C    Price: 650.50 Pages: 325
Title: C Pointers Price: 175.00 Pages: 225
Title: C Pearls   Price: 250.00 Pages: 250