企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# C 编程中的数组 > 原文: [https://beginnersbook.com/2014/01/c-arrays-example/](https://beginnersbook.com/2014/01/c-arrays-example/) 数组是相同数据类型的分组(或集合)。例如,`int`数组包含`int`类型的元素,而`float`数组包含`float`类型的元素。 ## 为什么我们需要在 C 编程中使用数组? 考虑一种情况,您需要找出用户输入的 100 个整数的平均值。在 C 中,您有两种方法可以执行此操作:1)使用`int`数据类型定义 100 个变量,然后执行 100 次`scanf()`操作以将输入的值存储在变量中,然后最后计算它们的平均值。 2)使用单个整数数组来存储所有值,循环数组以将所有输入的值存储在数组中,然后计算平均值。 **依你来看哪种解决方案更好?** 显然是第二种解决方案,将相同的数据类型存储在一个变量中以及稍后使用数组索引访问它们很方便(我们将在本教程后面讨论)。 ### 如何在 C 中声明数组 ```c int num[35];  /* An integer array of 35 elements */ char ch[10];  /* An array of characters for 10 elements */ ``` 类似地,数组可以是任何数据类型,例如`double`,`float`,`short`等。 ### 如何在 C 中访问数组的元素 您可以使用**数组下标**(或索引)来访问存储在数组中的任何元素。下标从 0 开始,这意味着`arr[0]`代表数组`arr`中的第一个元素。 通常,`arr[n-1]`可用于访问数组的第`n`个元素。其中`n`是任何整数。 **例如:** ```c int mydata[20]; mydata[0] /* first element of array mydata*/ mydata[19] /* last (20th) element of array mydata*/ ``` ### 数组示例:在 C 编程中找出 4 个整数的平均值 ```c #include <stdio.h> int main() { int avg = 0; int sum =0; int x=0; /* Array- declaration – length 4*/ int num[4]; /* We are using a for loop to traverse through the array * while storing the entered values in the array */ for (x=0; x<4;x++) { printf("Enter number %d \n", (x+1)); scanf("%d", &num[x]); } for (x=0; x<4;x++) { sum = sum+num[x]; } avg = sum/4; printf("Average of entered number is: %d", avg); return 0; } ``` 输出: ```c Enter number 1 10 Enter number 2 10 Enter number 3 20 Enter number 4 40 Average of entered number is: 20 ``` 让我们讨论上述程序的重要部分: #### 将数据输入数组 这里我们**将数组**从 0 迭代到 3,因为数组的大小是 4。在循环内部,我们向用户显示一条消息以输入值。使用`scanf`函数将所有输入值存储在相应的数组元素中。 ```c for (x=0; x<4;x++) { printf("Enter number %d \n", (x+1)); scanf("%d", &num[x]); } ``` #### 从数组中读出数据 假设,如果我们想要显示数组的元素,那么我们就可以在 C 中使用[`for`循环](https://beginnersbook.com/2014/01/c-for-loop/)。 ```c for (x=0; x<4;x++) { printf("num[%d]\n", num[x]); } ``` ### 各种初始化数组的方法 在上面的例子中,我们刚刚声明了数组,然后我们用用户输入的值初始化它。但是,您也可以在声明期间初始化数组,如下所示: ```c int arr[5] = {1, 2, 3, 4 ,5}; ``` 或(两者都相同) ```c int arr[] = {1, 2, 3, 4, 5}; ``` 未初始化的数组始终包含垃圾值。 ## C 数组 - 内存表示 ![c-arrays](https://img.kancloud.cn/9b/25/9b25a2cba49c86c1427289ab2f4af4a8_550x300.jpg) **关于 C 中数组的更多主题:** [**2D 数组**](https://beginnersbook.com/2014/01/2d-arrays-in-c-example/) - 我们可以在 C 中使用多维数组,如 2D 和 3D 数组。然而,最流行和最常用的数组是 2D - 二维数组。在这篇文章中,您将学习如何在 2D 数组中声明,读取和写入数据以及它的各种其他功能。 [**将数组传递给函数**](https://beginnersbook.com/2014/01/c-passing-array-to-function-example/) - 通常我们在调用函数时传递值和变量,同样我们也可以将数组传递给函数。您可以将数组的元素以及整个数组(通过仅指定数组名称,它用作指针)传递给函数。 [**指向数组的指针**](https://beginnersbook.com/2014/01/c-pointer-to-array-example/) - 可以使用 C 中的[指针](https://beginnersbook.com/2014/01/c-pointers/)访问和操作数组元素。使用指针可以轻松处理数组。只需将数组的基址分配给指针变量,就可以访问数组的所有元素。