Introduction to C language arrays (detailed explanation)

Array concept

The data stored in the array is related characters and strings, and we can approximately understand the data stored in the array as a set in mathematics.
The same is that the data of the array is the same as the elements of the collection, at least one element is in it.
In other words, one or more data is stored in the array, but the number of array elements cannot be 0.
But unlike collections, arrays can only store data of the same type, which means that if you store character types, you cannot store integer types at the same time.
Arrays are divided into one-dimensional arrays and multi-dimensional arrays. Multi-dimensional arrays are generally more common than two-dimensional arrays. Below we will introduce one-dimensional arrays and two-dimensional arrays in more detail.

one-dimensional array

Creation and initialization of one-dimensional arrays

Basic creation of one-dimensional arrays

 type arr_name[常量值];

1. The value stored in the array is called the element of the array
2. When the array is created, you can specify the size of the array and the element type of the array
• type specifies the type of data stored in the array, which
can be: char, short, int , float, etc.
can also be customized
• arr_name refers to the name of the array name.
The name can be meaningful according to the actual situation.
The constant value in [] is used to specify the size of the array.
The size of the array can be specified according to actual needs.
To make it easier to understand, let's give a practical example:

我们现在想存储某个班级的20⼈的数学成绩
那我们就可以创建⼀个数组
int math[20]={
    
    1,2,3,4,5.......}
现在我们想存储这20个人的名字
我们又可以创建一个数组
char name[20]={
    
    {
    
    "点赞关注"},{
    
    "快点赞关注!"}......
{
    
    "靓仔快点赞关注!"}}
/*{}中的字符串就是一个数据,为了方便区分
因此用{}括起来可以表明里面的数据为一个元素,
而不同于上一个int类型,因为字符串中有\0,
因此如果没有{}括起来,那么当遇到\0时,
将自动认为里面的数据已经读取完,
因此就不会再继续读取后面的数据。*/

Initialization of one-dimensional array

In fact, the understanding of initialization is very simple, that is, when creating an array, we need to give some initial values, which is called initialization.

例如:int a=1,b=2;
int arr[10]={
    
    1,2,3,4,5,6,7,8,9,10};
//数组的初始化⼀般使⽤⼤括号,将数据放在⼤括号中。

There are several situations for array initialization

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

//不完全初始化
int arr2[6] = {
    
    1};
/*第⼀个元素初始化为1,
剩余的元素默认初始化为0*/

//错误的初始化 - 初始化项太多
int arr3[3] = {
    
    1, 2, 3, 4};

the type of the array

Arrays also have types, and arrays can be regarded as a custom type. What remains after removing the array name is the type of the array. as follows:

int arr1[10];
int arr2[12];
char ch[5];
//arr1数组的类型是 int [10]
//arr2数组的类型是 int[12]
//ch 数组的类型是 char [5]

Use of one-dimensional arrays

After learning the basic syntax of one-dimensional arrays, one-dimensional arrays can store data, and the purpose of storing data is to operate on data, so how do we use one-dimensional arrays?

array subscript

The C language stipulates that arrays have subscripts, and the subscripts start from 0. Suppose the array has n elements, and the subscript of the last element is n-1. The subscript is equivalent to the number of the array element, as follows:

int arr[10] = {
    
    1,2,3,4,5,6,7,8,9,10};
arr[0]对应的就是1
arr[1]对应的就是2
......
arr[9]对应的就是10

There may be some doubts here, how should the 9 and 10 in arr[9] and arr[10] be judged as subscripts or numbers? In fact, the subscript indicates a specific data in the number, and it is not difficult to see that arr[10] contains 10 elements, so 10 must not be a subscript.
Array access in C language provides an operator [], this operator is called: subscript reference operator.
With the subscript access operator, we can easily access the elements of the array. For example, if we access the element with the subscript 7, we can use arr[7]. To access the element with the subscript 3, just You can use arr[3], the following code:

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	printf("%d\n", arr[7]);//结果为8
	printf("%d\n", arr[3]);//结果为4
	return 0;
}

Printing of array elements

Next, what if you want to access the contents of the entire array?
As long as we generate the subscripts of all elements of the array, then we use the for loop to generate subscripts from 0 to 9, and then use the subscripts to access.

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}
//最后的结果为1 2 3 4 5 6 7 8 9 10

array input

When it comes to input, we must think of the scanf function. If we use a loop, then we can input the desired data one by one.
Let's not talk nonsense between us:

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		scanf("%d", &arr[i]);
	}
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

Through the for loop, we can satisfy our continuous input data, of course, the while loop is also OK

#include<stdio.h>
int main()
{
    
    
	int arr[10]={
    
    1}, i = 0;
	while (i<10)
	{
    
    
		scanf("%d", &arr[i]);
		printf("%d ", arr[i]);
		i++;
	}
	return 0;

One-dimensional array storage in memory

With the previous knowledge, there are basically no obstacles for us to use arrays. If we want to understand arrays in depth, we'd better understand the storage of arrays in memory. Print the addresses of the array elements in turn:

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		printf("&arr[%d] = %p\n ", i, &arr[i]);//%p为数组的地址
	}
	return 0;
}

The result is shown in the figure.
insert image description here
From the output results, we analyze that the address of the array changes from small to large as the subscript increases, and we find that there is a difference of 4 between every two adjacent elements (because an integer is 4 words Festival). So we come to the conclusion that arrays are stored continuously in memory.

How to count the number of array elements with sizefo

When writing code, we often want to calculate the number of elements in a number, and using sizeof can just solve this
problem size. for example:

#include <stido.h>
int main()
{
    
    
	int arr[10] = {
    
     0 };
	printf("%d\n", sizeof(arr));
	return 0;
}
这⾥输出的结果是40,计算的是数组所占内存空间的总⼤⼩,单位是字节。

We know that all elements in the array are of the same type, so as long as the number of bytes occupied by an element is calculated, the number of elements in the array can be calculated. Here we choose the first element to calculate the size.

#include <stido.h>
int main()
{
    
    
	int arr[10] = {
    
     0 };
	printf("%d\n", sizeof(arr[0]));//计算⼀个元素的⼤⼩,单位是字节
	return 0;
}

Then you can calculate the number of elements in the array:

#include <stido.h>
int main()
{
    
    
	int arr[10] = {
    
     0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	printf("%d\n", sz);
	return 0;
}
这⾥的结果是:10,表⽰数组有10个元素。

In the future, there is no need to fix the number of array elements in the code. Using the above calculation, no matter how the array changes, the calculated
size will also change accordingly.

Two-dimensional array

The concept of two-dimensional numbers

The array learned earlier is called a one-dimensional array, and the elements of the array are all built-in types. If we use a one-dimensional array as the element of the array, then it is a two-dimensional array, and the array with the two-dimensional array as the array element is called Three-dimensional arrays, and arrays above two-dimensional arrays are collectively referred to as multidimensional arrays.
insert image description here

Creation of two-dimensional array

The specific format of a two-dimensional array is as follows:

type arr_name[常量值1][常量值2]
例如:
int arr[3][5];
double data[2][8];

The information appearing in the above code
• 3 means that the array has 3 lines
• 5 means that each line has 5 elements
• int means that each element of the array is an integer type • arr is the name of the array, you can specify the name data array meaning
according to your needs
Basically the same.

Initialization of two-dimensional array

The initialization of a two-dimensional array can refer to a one-dimensional array, which are enclosed in {} and given a value.
Here are a few examples:

不完全初始化
int arr1[3][5] = {
    
    1,2}int arr2[3][5] = {
    
    0}
 完全初始化
 int arr3[3][5] = {
    
    1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7}
 按照⾏初始化
 int arr4[3][5] = {
    
    {
    
    1,2},{
    
    3,4},{
    
    5,6}};
/*这里的详细解释会在*/二维数组在内存中的存储
 初始化时省略⾏,但是不能省略列
 int arr5[][5] = {
    
    1,2,3};
 int arr6[][5] = {
    
    1,2,3,4,5,6,7};
int arr7[][5] = {
    
    {
    
    1,2}, {
    
    3,4}, {
    
    5,6}};
/*这里的详细解释也会在*/ 二维数组在内存中的存储

Use of two-dimensional arrays

subscript of two-dimensional array

We assume that the two-dimensional array arr[10][10] is the same as the one-dimensional array. When the first [] is 0, it means the first row, and when the second [] is 0, it means the first column. Let us give an
example example:

int arr[3][3]={
    
    1,2,3, 2,3,4, 3,4,5}
arr[0][0]=1  arr[0][1]=2   arr[0][2]=3
arr[1][0]=2  arr[1][0]=3   arr[1][0]=4
arr[1][0]=3  arr[1][0]=4   arr[1][0]=5

In fact, we can also see the two-dimensional array as the xoy plane, the x-axis is the row, and the y-axis is the column (but the y-axis is along the negative direction, but there is no negative sign). Therefore, if we need to determine a point, we only need
to Enter the corresponding x value and y value in [ ].
Similarly, we can also apply a series of solving methods in mathematics to it.
Since the coordinates are all integers, we can set an equation that can only use integers, which can also be understood as Array
If we set an array such as:

arr[9][9]

If we need to find some coordinates such as

arr[0][1] arr[1][2] arr[2][3] arr[3][4]......
arr[7][8]

It is not difficult for us to see that the direct relationship between x and y is y=x+1, and the slope k is 1.
This is a simple example, just to show that we can try to combine mathematics to write code when solving some problems with code

Storage of two-dimensional arrays in memory

Like a one-dimensional array, if we want to study the storage method of a two-dimensional array in memory, we can also print out the addresses of all elements of the array. code show as below:

#include <stdio.h>
int main()
{
    
    
	int arr[3][5] = {
    
     0 };
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
    
    
		for (j = 0; j < 5; j++)
		{
    
    
			printf("&arr[%d][%d] = %p\n", i, j, &arr[i][j]);
		}
	}
	return 0;
}

The result of the operation is shown in the figure:
insert image description here
Here it is important to add that since the storage of the one-dimensional array is not mentioned,
the storage of the supplementary array here is actually in hexadecimal, that is to say, slow 16 into 1, what is hexadecimal? ?
Hexadecimal is a representation method of data in the computer, which is different from our daily decimal notation. It is composed of 0-9, AF, and the
corresponding relationship with decimal is:
0-9 corresponds to 0-9 ;
AF ​​corresponds to 10-15;

Combined with the int type mentioned in the one-dimensional array is 4 bytes, it is not difficult to see that the change of array storage changes in 4 bytes, so we infer: each element in each row
is Adjacent, there is a difference of 4 bytes between the addresses, and there is also a difference of 4 bytes between the two elements at the cross-row position (such as: arr[0][4] and arr[1][0]), so the two Each element in the dimensional array is stored contiguously. This also explains the problem in the previous two-dimensional array initialization

Variable-length arrays in C99

Before the C99 standard, when the C language created an array, the size of the array could only be specified using constants, constant expressions, or if we initialized the data, the size of the array could be omitted.
for example:

int arr1[10];
int arr2[3+5];
int arr3[] = {
    
    1,2,3};

Such grammatical restrictions make it inflexible for us to create arrays. Sometimes the array is too large to waste space, and sometimes the array is too small to use. The new feature
of a variable-length array in C99 allows us to use variables to specify the size of the array.
Take a look at the code below:

int n = a+b;
int arr[n];

In the above example, the array arr is a variable-length array, because its length depends on the value of the variable n, the compiler cannot determine in advance, and only the runtime can know the value of n.
The fundamental feature of variable-length arrays is that the length of the array can only be determined at runtime, so variable-length arrays cannot be initialized.
Its advantage is that programmers don't have to arbitrarily specify an estimated length for the array during development, and the program can assign an accurate length to the array at runtime.
There is a rather confusing point. The variable-length array means that the size of the array can be specified by a variable. When the program is running, the number of elements in the array is specified according to the size of the variable, not that the size of the array is Variable. Once the size of the array is determined, it cannot be changed.
Unfortunately, I use VS2022. Although it supports most of the syntax of C99, it does not support variable-length arrays in C99, but here is an example.

#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;
}

Array example (very important)

例子1:多个字符从两端移动,向中间汇聚
编写代码,演⽰多个字符从两端移动,向中间汇聚
#include <stdio.h>
int main()
{
    
    
	char arr1[] = "快点赞关注!!!!!";
	char arr2[] = "靓仔点赞关注!!";
	int left = 0;
	int right = strlen(arr1) - 1;
	printf("%s\n", arr2);
	while (left <= right)
	{
    
    
		Sleep(1000);
		arr2[left] = arr1[left];
		arr2[right] = arr1[right];
		left++;
		right--;
		printf("%s\n", arr2);
	}
	retutn 0;
}
例子2:⼆分查找
在⼀个升序的数组中查找制定的数字n,很容易想到的⽅法就是遍历数组,但是这种⽅法效率⽐较低,⽐如我买了⼀双鞋,你好奇问我多少钱,我说不超过300元。你还是好奇,你想知道到底多少,我就让你猜,于是你猜的头都大了还是没猜中,你会不会1234...这样猜,显然只有没给我点赞的人才会这样猜,对吗帅哥;点赞关注的人⼀般都会猜中间数字,⽐如:150,然后看⼤了还是⼩了,这就是⼆分查找,也叫折半查找。
#include <stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int left = 0;
	int right = sizeof(arr) / sizeof(arr[0]) - 1;
	int key = 7;//要找的数字
	int mid = 0;//记录中间元素的下标
	int find = 0;
	while (left <= right)
	{
    
    
		mid = (left + right) / 2;
		if (arr[mid] > key)
		{
    
    
			right = mid - 1;
		}
		else if (arr[mid] < key)
		{
    
    
			left = mid + 1;
		}
		else
		{
    
    
			find = 1;
			break;
		}
	}
	if (1 == find)
		printf("快点赞关注", mid);
	else
		printf("你怎么还没有点赞关注\n");
}
求中间元素的下标,使⽤ mid = (left+right)/2 ,如果left和right⽐较⼤的时候可能存在问题,可以使⽤下⾯的⽅式:
1 mid = left+(right-left)/2;

Summarize

Finally, let's make a small summary. One-dimensional arrays and multi-dimensional arrays are actually quite similar, such as two-dimensional arrays. We can compare the two to learn, so that the learning speed will be faster.
What's more, you have seen this, so can't you pay attention and like it by the way? ? ? ?

Guess you like

Origin blog.csdn.net/2301_79178723/article/details/132109688