📜  C-数组

📅  最后修改于: 2020-12-19 05:27:42             🧑  作者: Mango


数组是一种数据结构,可以存储相同类型的元素的固定大小的顺序集合。数组用于存储数据的集合,但是将数组视为相同类型的变量的集合通常会更有用。

无需声明单个变量(例如number0,number1,…和number99),而是声明一个数组变量(例如numbers),并使用numbers [0],numbers [1]和…,numbers [99]表示各个变量。数组中的特定元素由索引访问。

所有阵列均包含连续的内存位置。最低地址对应于第一个元素,最高地址对应于最后一个元素。

C中的数组

声明数组

为了用C声明一个数组,程序员指定元素的类型和数组所需的元素数量,如下所示:

type arrayName [ arraySize ];

这称为一数组。 arraySize必须是一个大于零的整数常量,并且type可以是任何有效的C数据类型。例如,要声明一个称为double类型的balance的10元素数组,请使用以下语句-

double balance[10];

这里的balance是一个变量数组,足以容纳10个双数。

初始化数组

您可以在C中一个接一个地初始化数组,也可以使用单个语句来初始化数组,如下所示:

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

大括号{}之间的值数不能大于我们为方括号[]之间的数组声明的元素数。

如果省略数组的大小,则会创建一个大小足以容纳初始化的数组。因此,如果您写-

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

您将创建与上一个示例完全相同的数组。以下是分配数组的单个元素的示例-

balance[4] = 50.0;

上面的语句为数组中的5元素赋值为50.0。所有数组的第一个元素的索引均为0,也称为基本索引,而数组的最后一个索引为数组的总大小减去1。下面显示的是我们上面讨论的数组的图形表示-

阵列展示

访问数组元素

通过索引数组名称来访问元素。这是通过将元素的索引放在数组名称后面的方括号内来完成的。例如-

double salary = balance[9];

上面的语句将从数组中获取第10元素,并将值分配给salary变量。以下示例显示如何使用上述所有三个概念。声明,赋值和访问数组-

#include 
 
int main () {

   int n[ 10 ]; /* n is an array of 10 integers */
   int i,j;
 
   /* initialize elements of array n to 0 */         
   for ( i = 0; i < 10; i++ ) {
      n[ i ] = i + 100; /* set element at location i to i + 100 */
   }
   
   /* output each array element's value */
   for (j = 0; j < 10; j++ ) {
      printf("Element[%d] = %d\n", j, n[j] );
   }
 
   return 0;
}

编译并执行上述代码后,将产生以下结果-

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

详细数组

数组对C很重要,应该多加注意。 C程序员应该清楚以下与数组有关的重要概念-

Sr.No. Concept & Description
1 Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array’s name without an index.

3 Return array from a function

C allows a function to return an array.

4 Pointer to an array

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.