Cprogramming 简明教程
Arrays in C
C 中的数组是一种数据结构,可以存储相同 data type 的元素的固定大小的顺序集合。数组用于存储集合的数据,但通常把数组当作相同类型的变量集合更实用。
Arrays in C are a kind of data structure that can store a fixed-size sequential collection of elements of the same data type. Arrays are used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
What is an Array in C?
C 中的数组是具有类似数据类型的相似数据项的集合。数组中可以存储一个或多个值相同的数据类型,它可能是主数据类型(int、float、char)或用户定义的类型(如结构或指针)。在 C 中,数组中元素的类型应与数组本身的数据类型匹配。
An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C, the type of elements in the array should match with the data type of the array itself.
数组的大小(也称为数组的长度)必须在声明本身中指定。一旦声明,C 数组的大小就不能更改。当声明数组时,编译器会分配存储已声明数量的元素所需的连续内存块。
The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared, the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of memory required to store the declared number of elements.
Why Do We Use Arrays in C?
数组用于存储和操作相似类型的数据。
Arrays are used to store and manipulate the similar type of data.
假设我们想要存储 10 个学生的成绩并求平均分。我们声明 10 个不同的变量来存储 10 个不同的值,如下所示 −
Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store 10 different values as follows −
int a = 50, b = 55, c = 67, . . . ;
float avg = (float)(a + b + c +. . . ) / 10;
这些变量将分散在内存中,彼此之间没有关系。重要的是,如果我们想要扩展查找 100 个(或更多)学生的平均分的问题,那么声明如此多的单个变量就不切实际了。
These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many individual variables.
数组提供了一种紧凑且节省内存的解决方案。由于数组中的元素存储在相邻的位置,因此我们可以轻松地相对于当前元素访问任何元素。由于每个元素都有一个索引,因此可以对其进行直接操作。
Arrays offer a compact and memory-efficient solution. Since the elements in an array are stored in adjacent locations, we can easily access any element in relation to the current element. As each element has an index, it can be directly manipulated.
Example: Use of an Array in C
为了回到存储 10 个学生的成绩并求平均分的问题,使用数组的解决方案如下 −
To go back to the problem of storing the marks of 10 students and find the average, the solution with the use of array would be −
#include <stdio.h>
int main(){
int marks[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51};
int i, sum = 0;
float avg;
for (i = 0; i <= 9; i++){
sum += marks[i];
}
avg = (float)sum / 10;
printf("Average: %f", avg);
return 0;
}
Output
运行代码并检查其输出:
Run the code and check its output −
Average: 52.000000
数组元素存储在连续的内存位置中。每个元素由从“0”开始的索引标识。最低地址对应于第一个元素,最高地址对应于最后一个元素。
Array elements are stored in contiguous memory locations. Each element is identified by an index starting with "0". The lowest address corresponds to the first element and the highest address to the last element.
Declaration of an Array in C
要在 C 中声明一个数组,你需要指定元素的类型和要存储在其中的元素数量。
To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in it.
Syntax to Declare an Array
type arrayName[size];
“size”必须大于零的整型常量,其“type”可以是任何有效的 C 数据类型。有不同的方法可以在 C 中声明数组。
The "size" must be an integer constant greater than zero and its "type" can be any valid C data type. There are different ways in which an array is declared in C.
Example: Declaring an Array in C
在下面的示例中,我们声明一个包含 5 个整数的数组,并打印所有数组元素的索引和值 −
In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array elements −
#include <stdio.h>
int main(){
int arr[5];
int i;
for (i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
a[0]: -133071639
a[1]: 32767
a[2]: 100
a[3]: 0
a[4]: 4096
Initialization of an Array in C
声明数组时,可以通过提供用花括号 {} 括起来的、以逗号分隔的值集来初始化它。
At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed within the curly braces {}.
Example to Initialize an Array
以下示例演示了整数数组的初始化:
The following example demonstrates the initialization of an integer array:
// Initialization of an integer array
#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
int i; // loop counter
// Printing array elements
printf("The array elements are : ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Output
The array elements are : 10 20 30 40 50
Example of Initializing all Array Elements to 0
要将所有元素初始化为 0,请将其放在花括号内
To initialize all elements to 0, put it inside curly brackets
#include <stdio.h>
int main(){
int arr[5] = {0};
int i;
for(i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
return 0;
}
Output
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
a[0]: 0
a[1]: 0
a[2]: 0
a[3]: 0
a[4]: 0
Example of Partial Initialization of an Array
如果值列表小于数组的大小,则其余元素将初始化为“0”。
If the list of values is less than the size of the array, the rest of the elements are initialized with "0".
#include <stdio.h>
int main(){
int arr[5] = {1,2};
int i;
for(i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
return 0;
}
Output
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
a[0]: 1
a[1]: 2
a[2]: 0
a[3]: 0
a[4]: 0
Example of Partial and Specific Elements Initialization
如果数组部分初始化,则可以在方括号中指定元素。
If an array is partially initialized, you can specify the element in the square brackets.
#include <stdio.h>
int main(){
int a[5] = {1,2, [4] = 4};
int i;
for(i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, a[i]);
}
return 0;
}
Output
在执行时,它会产生以下输出 −
On execution, it will produce the following output −
a[0]: 1
a[1]: 2
a[2]: 0
a[3]: 0
a[4]: 4
Getting Size of an Array in C
编译器将分配一个连续的内存块。分配的内存大小取决于数组的数据类型。
The compiler allocates a continuous block of memory. The size of the allocated memory depends on the data type of the array.
Example 1: Size of Integer Array
如果声明了一个 5 个元素的整数数组,则以字节为单位的数组大小将为“sizeof(int) x 5”
If an integer array of 5 elements is declared, the array size in number of bytes would be "sizeof(int) x 5"
#include <stdio.h>
int main(){
int arr[5] = {1, 2, 3, 4, 5};
printf("Size of array: %ld", sizeof(arr));
return 0;
}
Output
执行后,将得到以下输出 −
On execution, you will get the following output −
Size of array: 20
sizeof 运算符返回变量占用的字节数。
The sizeof operator returns the number of bytes occupied by the variable.
Example 2: Adjacent Address of Array Elements
每个 int 的大小是 4 个字节。编译器为每个元素分配相邻位置。
The size of each int is 4 bytes. The compiler allocates adjacent locations to each element.
#include <stdio.h>
int main(){
int a[] = {1, 2, 3, 4, 5};
int i;
for(i = 0; i < 4; i++){
printf("a[%d]: %d \t Address: %d\n", i, a[i], &a[i]);
}
return 0;
}
Output
运行代码并检查其输出:
Run the code and check its output −
a[0]: 1 Address: 2102703872
a[1]: 2 Address: 2102703876
a[2]: 3 Address: 2102703880
a[3]: 4 Address: 2102703884
在此数组中,每个元素的类型都为 int 。因此,第 0 个元素占据从 642016 到 19 的前 4 个字节。下一个下标处的元素占据接下来的 4 个字节,依此类推。
In this array, each element is of int type. Hence, the 0th element occupies the first 4 bytes 642016 to 19. The element at the next subscript occupies the next 4 bytes and so on.
Example 3: Array of Double Type
如果我们有 double 类型的数组,那么每个下标处的元素将占据 8 个字节
If we have the array type of double type, then the element at each subscript occupies 8 bytes
#include <stdio.h>
int main(){
double a[] = {1.1, 2.2, 3.3, 4.4, 5.5};
int i;
for(i = 0; i < 4; i++){
printf("a[%d]: %f \t Address: %ld\n", i, a[i], &a[i]);
}
return 0;
}
Output
运行代码并检查其输出:
Run the code and check its output −
a[0]: 1.100000 Address: 140720746288624
a[1]: 2.200000 Address: 140720746288632
a[2]: 3.300000 Address: 140720746288640
a[3]: 4.400000 Address: 140720746288648
Example 4: Size of Character Array
“char”变量的长度为 1 个字节。因此,char 数组长度将等于数组大小。
The length of a "char" variable is 1 byte. Hence, a char array length will be equal to the array size.
#include <stdio.h>
int main(){
char a[] = "Hello";
int i;
for (i=0; i<5; i++){
printf("a[%d]: %c address: %ld\n", i, a[i], &a[i]);
}
return 0;
}
Output
运行代码并检查其输出:
Run the code and check its output −
a[0]: H address: 6422038
a[1]: e address: 6422039
a[2]: l address: 6422040
a[3]: l address: 6422041
a[4]: o address: 6422042
Accessing Array Elements in C
数组中的每个元素都由唯一的递增索引标识,从“0”开始。要通过索引访问元素,这是通过在数组名称后将元素索引放在方括号内完成的。
Each element in an array is identified by a unique incrementing index, stating with "0". To access the element by its index, this is done by placing the index of the element within square brackets after the name of the array.
通过在数组名称后方括号内指定所需元素的索引(偏移量)来访问数组元素。例如 −
The elements of an array are accessed by specifying the index (offset) of the desired element within the square brackets after the array name. For example −
double salary = balance[9];
上面的语句将从数组中获取第 10 个元素并将值赋给“salary”。
The above statement will take the 10th element from the array and assign the value to the "salary".
Example to Access Array Elements in C
以下示例演示了如何使用上述三个概念,即声明、赋值和访问数组。
The following example shows how to use all the three above-mentioned concepts viz. declaration, assignment, and accessing arrays.
#include <stdio.h>
int main(){
int n[5]; /* n is an array of 5 integers */
int i, j;
/* initialize elements of array n to 0 */
for(i = 0; i < 5; i++){
n[i] = i + 100;
}
/* output each array element's value */
for(j = 0; j < 5; j++){
printf("n[%d] = %d\n", j, n[j]);
}
return 0;
}
Output
运行此代码,您将获得以下输出−
On running this code, you will get the following output −
n[0] = 100
n[1] = 101
n[2] = 102
n[3] = 103
n[4] = 104
该索引允许随机访问数组元素。数组可以包含结构变量、指针甚至其他数组作为其元素。
The index gives random access to the array elements. An array may consist of struct variables, pointers and even other arrays as its elements.
More on C Arrays
数组作为 C 中的一个重要概念,需要更多关注。对于 C 程序员来说,与数组相关的以下重要概念应该清楚 −
Arrays, being an important concept in C, need a lot more attention. The following important concepts related to arrays should be clear to a C programmer −
Sr.No |
Concept & Description |
1 |
Multi-dimensional arraysC supports multidimensional arrays. The simplest form of an multidimensional array is the two-dimensional array. |
2 |
Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array’s name without an index. |
3 |
Return array from a functionC allows a function to return an array. |
4 |
Pointer to an arrayYou can generate a pointer to the first element of an array by simply specifying the array name, without any index. |