C - 数组的属性
数组是 C 语言中非常重要的数据结构。在 C 语言程序中使用数组可以更轻松地处理大量数据。由于数组拥有丰富的属性,因此相比单个变量,数组拥有许多优势。数组的大多数重要属性都源于其组合:数组是相同数据类型值的集合,位于连续的内存块中。
不同编程语言中的数组属性可能会有所不同。在 C 编程语言中,数组的主要属性如下:
- 相同数据类型的集合
- 连续的内存分配
- 固定大小
- 长度取决于类型
- 索引
- 指针关系
- 上下界
- 多维数组
- 复杂数据结构的实现
让我们详细讨论每个属性。
相同数据类型的集合
数组的所有元素必须属于相同的数据类型。这确保了对数据的访问和操作的一致性。
如果数组声明如下 -
int arr[] = {50, 67.55, "hello", 21};
编译器会发出警告 -
将"char *"初始化为"int",无需强制类型转换即可将指针转换为整数 [-Wint-conversion]|
连续内存分配
数组的所有元素都存储在连续的内存位置,这意味着它们占用彼此相邻的内存块。这允许高效的随机访问和内存管理。

固定大小
数组的大小在声明时固定,在程序执行过程中无法更改。这意味着您需要事先知道所需的最大元素数量。在 C 语言中,数组的大小不能通过变量定义。
//这是可以接受的
#define SIZE = 10 int arr[SIZE];
//这也是可以接受的
const SIZE = 10; int arr[SIZE];
//此操作不被接受
int SIZE = 10; int arr[SIZE];
//大小必须是整数。这将引发错误
float num[10.5] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51};
长度取决于类型
由于数组可以存储所有相同类型的元素,因此其占用的总内存取决于数据类型。
示例
#include<stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; int size = sizeof(num) / sizeof(int); printf("element at lower bound num[0]: %d ", num[0]); printf("at upper bound: %d byte ", num[size-1]); printf("length of int array: %ld ", sizeof(num)); double nm[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; size = sizeof(nm) / sizeof(double); printf("element at lower bound nm[0]: %f ", nm[0]); printf("element at upper bound: %f ", nm[size-1]); printf("byte length of double array: %ld ", sizeof(nm)); return 0; }
输出
element at lower bound num[0]: 50 at upper bound: 51 byte length of int array: 40 element at lower bound nm[0]: 50.000000 element at upper bound: 51.000000 byte length of double array: 80
索引
数组中的每个元素都有一个唯一的索引,从 0 开始。您可以使用方括号内的索引访问各个元素。通常,使用for 循环遍历数组,该循环遍历数组的长度,并使用循环变量作为索引。
示例
#include <stdio.h> int main() { int a[] = {1,2,3,4,5}; int i; for (i=0; i<4; i++){ printf("a[%d]: %d ", i, a[i]); } return 0; }
指针关系
数组的名称相当于指向其第一个元素的常量指针。这使得您可以在特定上下文中互换使用数组名称和指针。
示例
#include <stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; printf("num[0]: %d Address of 0th element: %d ", num[0], &num[0]); printf("Address of array: %d", num); return 0; }
输出
num[0]: 50 Address of 0th element: 6422000 Address of array: 6422000
下限和上限
数组中的每个元素都由一个从 0 开始的索引标识。数组的下限是其第一个元素的索引,该索引始终为 0。数组中最后一个元素的索引为 size -1。
示例
#include <stdio.h> int main() { int num[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; int size = sizeof(num) / sizeof(int); printf("element at lower bound num[0]: %d at upper bound: %d Size of array: %d", num[0], num[size-1], size); return 0; }
输出
element at lower bound num[0]: 50 at upper bound: 51 Size of array: 10
多维数组
用方括号声明一个大小值,这种数组称为一维数组。在一维数组中,每个元素由其索引或下标标识。在 C 语言中,可以使用多个索引声明,以模拟二维、三维或多维数组。
示例
例如,以下是一个二维数组的示例 -
int a[3][3] = { {1, 2, 3}, {11, 22, 33}, {111, 222, 333}};
你可以将一维数组视为列表,将二维数组视为表格或矩阵。理论上,数组的维数没有限制,但在实际应用中,二维数组常用于电子表格、数据库等的设计。
复杂数据结构的实现
我们可以在结构体数据类型的构造中使用数组来实现诸如堆栈、链表和树等数据结构。
示例
typedef struct stack { int top; int arr[10]; } Stack;
因此,数组是程序员工具库中的一个重要工具,因为它可以用于不同的应用程序。C 语言中的数组概念被许多后续编程语言(例如 C++、C#、Java 等)所实现。