7. Arrays (one-dimensional arrays, two-dimensional arrays, variable-length arrays in C99, binary search method)

1. The concept of array

An array is a collection of elements of the same type. Its characteristics are:
1. The array stores one or more data, but the number of array elements cannot be 0.
2. Multiple data stored in the array are of the same type
. They are one-dimensional arrays and multi-dimensional arrays, and most arrays are generally two-dimensional arrays.

2. One-dimensional array

2.1 Creation of one-dimensional array

Format: data type array name [constant value];
example int num[10];

2.2 Types of one-dimensional arrays

After removing the array name, what remains is the array type, for example int num[10]; the array type is int [10]. The
data type of the array elements can be char, int, float, etc. The data types of the elements in the array are the same.

2.3 Initialization of one-dimensional array

//完全初始化
int num[5] = {
    
    1,2,3,4,5};

//不完全初始化,除了1 2 3,剩下的其余元素都默认为0
int num[5] = {
    
    1,2,3};

//初始化1 2 3,长度也为3
int num[] = {
    
    1,2,3};

2.4 Subscripts in one-dimensional arrays

In C language, an operator [ ] is provided for array access. This operator is called: subscript reference operator. Pay attention to the difference between the constants in [ ] when
defining the array and when calling the array elements.
The constants in the definition represent the elements. The number of constants
inside represents the array subscript when called, that is, the index
bit array subscript starts counting from 0.
Insert image description here

Example:

//注意区分 定义数组时 和 访问数组元素时 []的区别
int num[5] = {
    
    1,2,3,4,5};//这里num[5]表示的是数组长度为5
printf("数组下标为4的值:%d", num[4]);//这里num[4]表示的是访问数组下标为4的数组元素

Output results
Insert image description here

2.5 Input and output of one-dimensional array

output

//输出
int main() {
    
    
	int arr[9] = {
    
    1,2,3,4,5,6,7,8,9};
	for (int i = 0; i < 9; i++)//这里小于9是因为长度为9的数组 下标范围为0~8
	{
    
    
		printf("arr[%d] = %d\n",i,arr[i]);
	}
	return 0;
}

Output results
Insert image description here


enter

//输入
int main() {
    
    
	int arr[9];
	for (int i = 0; i < 9; i++)
	{
    
    
		scanf("%d",&arr[i]);
	}

	for (int i = 0; i < 9; i++)//这里小于9是因为长度为9的数组 下标范围为0~8
	{
    
    
		printf("arr[%d] = %d\n",i,arr[i]);
	}
	return 0;
}

Enter results
Insert image description here

2.6 Storage of one-dimensional array in memory

The storage address of a one-dimensional array in memory increases from small to large as the subscript increases. The
array is stored continuously in memory . Taking an integer array as an example, the difference between each two adjacent array elements is 4 (because An integer is 4 bytes)

int main() {
    
    
	int arr[9] = {
    
    1,2,3,4,5,6,7,8,9};
	for (int i = 0; i < 9; i++)
	{
    
    
		printf("arr[%d] = %p\n",i,&arr[i]);
	}
	return 0;
}

Output results (in 32-bit (x86) environment)
Insert image description here

The hexadecimal form represents the address stored in the memory. The difference between each data element is 4 because it is an int type data element.

2.7 Use sizeof() to calculate the number of array elements

The sizeof() function is a keyword in C language
. Its function is to calculate the size of a type or variable.
The unit is byte.

Because all elements in the array are of the same data type , each data element is the same size
That is: the total size of the memory space occupied / the data type of the corresponding array element = the number of elements in the array

int main() {
    
    
	int arr[10] = {
    
    0};//这里我们就非完全初始化数组,所以我们不知道数组有多少个元素个数
	printf("数组 int arr[10] 所占内存空间的总大小:%zd 字节\n",sizeof(arr));
	printf("数组 int arr[10] 其中一个数组元素所占内存空间的大小:%zd 字节\n",sizeof(arr[0]));
	
	//所占内存空间总大小 / 对应数组元素的数据类型 = 数组内元素的个数
	int sum = sizeof(arr) / sizeof(arr[0]);
	printf("数组中元素的个数:%d", sum);

	return 0;
}

Output results
Insert image description here

3. Two-dimensional array

3.1 Concept of two-dimensional array

Two-dimensional array: It is equivalent to using a one-dimensional array as an array element. In this case, it is a two-dimensional array. By
analogy, a three-dimensional array is an array in which a two-dimensional array is used as an array element. Arrays
above two-dimensional arrays are collectively called multi-dimensional arrays.

3.2 Creation of two-dimensional array

Format: data type array name [constant value 1] [constant value 2];
example:
int num[10][10];
the first 10 means that the array has 10 rows,
the second 10 means that each row has 10 array elements

3.3 Initialization of two-dimensional array

// 不完全初始化
int arr1[3][3] = {
    
    1,2,3};
int arr2[3][3] = {
    
    0};

// 完全初始化
int arr3[3][3] = {
    
    1,2,3, 4,5,6, 7,8,9};

//按照行初始化
int arr4[3][3] = {
    
    {
    
    1,2,3},{
    
    4,5,6},{
    
    7,8,9}};

//初始化时可以省略行,但是不能省略列
int arr5[][3] = {
    
     1,2 };
int arr6[][3] = {
    
     1,2,3,4,5};
int arr7[][3] = {
    
     {
    
    1,2},{
    
    4,5},{
    
    7,8} };

3.4 Subscripts in two-dimensional arrays

The subscripts of the rows in the two-dimensional array start from 0, and the coordinates of the columns also start from 0. When
initializing, the rows can be omitted, but the columns cannot be omitted,
that is, int man[can be omitted][cannot be omitted];

3.5 Input and output of two-dimensional array

enter

	//输入
	for (int i = 0; i < 3; i++)//行号
	{
    
    
		for (int j = 0; j < 3; j++)//列号
		{
    
    
			scanf("%d ", &arr[i][j]);//记得加&
		}
	}

output

	//输出
	for (int i = 0; i < 3; i++)//行号
	{
    
    
		for (int j = 0; j < 3; j++)//列号
		{
    
    
			printf("%d ", arr[i][j]);
		}
		printf("\n");
	}

3.6 Storage of two-dimensional arrays in memory

Each element in each row of a two-dimensional array is adjacent.
Taking integers as an example,
the difference between each two adjacent array elements is 4 bytes (because an integer is 4 bytes) at the
cross-row connection. Each element is only 4 bytes different, so the two-dimensional array is also stored continuously in memory.

int main() {
    
    
	int arr[3][3] = {
    
     {
    
    1,2,3},{
    
    4,5,6},{
    
    7,8,9} };
	for (int i = 0; i < 3; i++)//行号
	{
    
    
		for (int j = 0; j < 3; j++)//列号
		{
    
    
			printf("arr[%d][%d] = %p\n", i, j, &arr[i][j]);
		}
		printf("\n");
	}
	return 0;
}

Output results
Insert image description here

3.Variable length array in C99

Before the C99 standard, when creating an array in C language, the array size must be expressed by a constant or a constant expression, or the array size must be omitted when initializing the array and the array elements must be entered directly.

1.用常量来表示数组大小
int arr[5];
2.省略数组大小,开始直接自己输入元素
int arr[] = {
    
    1,2,3,4,5};

Creating an array in this way will bring very big restrictions, that is, the size of the array cannot be changed flexibly, and the size of the array must be hard-coded at the beginning.

All the new features given in C99 are a variable-length array (VLA) , allowing us to use variables to create array sizes.

//这样一来就可以根据输入的值来创建对应的大小的数组了
int n;
scanf("%d",&n)
int arr[n];

In the above example, arr is an array of side lengths. Its array size depends on the size of the input value n. The compiler cannot determine the array size in advance. It can only know what n is when the program is running. ( That is, the size of the variable-length array can only be determined at runtime, so the variable-length array cannot be initialized. )
Advantages: When developing a program, there is no need to specifically consider defining the size range of the array, etc. The program can accurately determine the size of the array at runtime. The size of the array is allocated based on the assignment to the variable.
Notice:When the program is running, the size of the array is allocated according to the size of the variable. Once the size of the array is allocated, it is determined not to change.(Variable means that the variable when creating the array is variable and does not need a unique fixed value; it does not mean that the size of the array can be changed at will) Unfortunately,


most C99 syntax is supported on VS2022, but C99 syntax is not supported in VS. variable length array

#include <stdio.h>
int main(){
    
    
	int n = 0;
	scanf("%d", &n);//根据输⼊数值确定数组的⼤⼩
	int arr[n];
	int i = 0;
	for (i = 0; i < n; i++){
    
    
		scanf("%d", &arr[i]);
	}
	for (i = 0; i < n; i++){
    
    
		printf("%d ", arr[i]);
	}
return 0;
}

Input:
5
1 2 3 4 5

Output:
1 2 3 4 5

4. Binary search method (also called half search method)

Compare with traditional search methods

It starts from the element with array subscript 0, and increases it gradually to compare with the number to be found.
Disadvantages: If the number to be found is large, tens of thousands, then it will have to be searched tens of thousands of times; the larger the number to be searched, The larger the search, the more difficult it will be

//传统查找方式(麻烦,什么年代了还在用传统香。。。方法)
int main() {
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int k = 0;//要查找的数
	int count = 1;//查找次数
	scanf("%d", &k);
	
	int sz = sizeof(arr) / sizeof(arr[0]);//数组内元素个数

	int find = 0;//假设找不到

	int i = 0;
	//循环递增数组下标作比较
	for (i = 0; i < sz; i++)
	{
    
    
		if (k == arr[i]) {
    
    
			printf("成功找到arr[%d]=%d,共查找了%d次", i,arr[i],count);
			find = 1;
			break;
		}
		count++;
	}
	if (find == 0)
	{
    
    
		printf("查找了%d次,找不到",count);
	}
	return 0;
}

Insert image description here


binary search method

开始:
将列表的起始索引 low 设置为 0
将列表的结束索引 high 设置为数组长度减1

循环条件为(low 小于等于 high):
    将中间索引 mid 设置为 (low + high) 的一半
    
   如果列表的mid下标对应的元素小于目标值:
        将 low 设置为 mid 加 1
   如果列表的mid下标对应的元素大于目标值:
        将 high 设置为 mid 减 1
   否则(也就是low 等于 high 时):
   		mid 下标对应的元素 等于 目标值
   		退出循环
//二分查找
int main() {
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int k = 0;//要查找的数
	scanf("%d", &k);
	int count = 1;//查找次数
	int find = 0;//假设找不到

	int sz = sizeof(arr) / sizeof(arr[0]);//数组内元素个数(组数长度)

	//low和high都是指下标位置
	int low = 0;
	int high = sz - 1;

	while (low <= high)
	{
    
    
		int mid = (low + high) / 2;

		//以下方法为 int mid = low + high 的优化方法:
		//之所以这么写是为了防止数据类型超出上限
		//int mid = low + (high - low)/2;

		if (arr[mid] < k)
		{
    
    
			low = mid + 1;
			count++;
		}
		else if (arr[mid] > k) {
    
    
			high = mid - 1;
			count++;
		}
		else
		{
    
    
			printf("成功找到arr[%d]=%d,共查找了%d次", mid, arr[mid], count);
			find = 1;
			break;
		}
	}
	if (find == 0)
	{
    
    
		printf("找不到");
	}
	return 0;
}

Insert image description here

Take int arr[] = { 1,2,3,4,5,6,7,8,9,10}; as an example.
Although the difference between the traditional search method 6 times and the binary search method 3 times is not particularly big,
as the array As the size of the binary search increases, the efficiency advantage of binary search will become more and more obvious.

Guess you like

Origin blog.csdn.net/qq_45657848/article/details/132014201