[C Language Elementary] ❤️ A blog directly handles the array (very comprehensive + recommended collection) ❤️

Kind tips

Hello everyone, I am Cbiltps. In my blog, if there are sentences that are difficult to understand or key points that are difficult to express in words , I will have pictures . So my blog with pictures is very important ! ! !

If you are interested in me please see my first blog !

Key points of this chapter

  1. Creation and initialization of one-dimensional arrays
  2. Use of one-dimensional arrays
  3. Storage of one-dimensional arrays in memory
  4. Creation and initialization of two-dimensional arrays
  5. Use of two-dimensional arrays
  6. Storage of two-dimensional arrays in memory
  7. Array out of bounds
  8. array as function parameter
  9. Application example 1 of arrays: three chess
  10. Array Application Example 2: Minesweeper Game

start of text


1. Creation and initialization of one-dimensional array


1.1 Array creation

An array is a collection of elements of the same type .

How the array is created:

type_t arr_name [const_n];

//type_t 是数组的元素类型
//arr_name 是数组名
//const_n 是一个常量表达式,用来指定数组的大小

An instance of array creation:

//代码1
int arr1[10];

//代码2
int count = 10;
int arr2[count];//注意:C99之后允许数组大小使用变量,叫变常数组

//代码3
char arr3[10];
float arr4[1];
double arr5[20];

Note: To create an array, []a constant must be given in it, and variables cannot be used (before C99).

1.2 Array initialization

The initialization of the array refers to: while creating the array, give some reasonable initial values ​​(initialization) to the contents of the array .

Look at the code:

int arr1[10] = {
    
    1,2,3};//不完全初始化,剩余的默认初始化为0
int arr2[] = {
    
    1,2,3,4};//这里的[]是没有指定大小,是根据初始化的内容确定它的值

char arr3[3] = {
    
    'a',98, 'c'};//对于字符数组,中间的元素依旧是b,因为对应的ASCII码值是98
char arr4[] = {
    
    'a','b','c'};//里面没有\0
char arr5[] = "abc";//注意:这个数组里的元素是a,b,c和\0

Note: If the array is not initialized when it is created, if it is a local variable, there will be nothing in it (that is, a randomly assigned value); if it is a global variable, it will be 0 by default.

When the array is created, if you do not want to specify the size of the array, you must initialize it. The number of elements in the array is determined according to the initialization content.

1.3 Use of one-dimensional arrays

For the use of arrays, we introduced an operator before: [], the subscript reference operator , which is an operator for array access.

Let's look at the code:

#include <stdio.h>

int main()
{
    
    
    int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10,11,12,13 };
	int i = 0;
	//计算数组元素个数
	int sz = sizeof(arr) / sizeof(arr[0]);
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}

	return 0;
}

If you don't understand, please look at the picture:
insert image description here
Summary:

  1. Arrays are accessed using subscripts, which start at 0.
  2. The size of the array can be calculated.
int arr[10];
int sz = sizeof(arr)/sizeof(arr[0]);//这样计算数组的大小

1.4 Storage of one-dimensional arrays in memory

Next we discuss the storage of arrays in memory.

Please see the code:

#include <stdio.h>

int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	//计算数组元素个数
	int sz = sizeof(arr) / sizeof(arr[0]);

	for (i = 0; i < sz; i++)
	{
    
    
		printf("%p\n", &arr[i]);
	}

	return 0;
}

The operation diagram is as follows:
insert image description here

Carefully observe the output results, we know that as the array subscript increases, the address of the element also increases regularly.
It can be concluded from this that the array is stored continuously in memory.


2. Creation and initialization of two-dimensional array


2.1 Creation of two-dimensional array

int arr[3][4];//表示三行四列
char arr[3][5];
double arr[2][4];

Drawing comprehension:
insert image description here

2.2 Initialization of two-dimensional array

int arr[3][5] = {
    
    1,2,3,4,5,6,7,8,9,10,11};
int arr[3][5] = {
    
    {
    
    1,2},{
    
    3,4},{
    
    5,6}};
int arr[][5] = {
    
    {
    
    1,2},{
    
    3,4},{
    
    5,6}};//可以省略行,不能省略列
//以下是错误的演示
//int arr[3][] = {
    
    {1,2},{3,4},{5,6}}; 错误一
//int arr[][5]; 错误二

char ch1[4][6] = {
    
     'a', 'b' };
char ch2[4][6] = {
    
     {
    
    'a'},{
    
     'b'} };
char ch3[4][6] = {
    
    "abc", "def", "qwe"};

Drawing comprehension:
insert image description here

2.3 Use of two-dimensional arrays

The use of two-dimensional arrays is also through subscripts .

#include <stdio.h>

int main()
{
    
    

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

	return 0;
}

operation result:
insert image description here

2.4 Storage of two-dimensional arrays in memory

Like 1D array, here we try to print the address of each element of 2D array.

#include <stdio.h>

int main()
{
    
    

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

	return 0;
}

The running results are as follows:
insert image description here
Through the results, we can analyze that, in fact, two-dimensional arrays are also stored continuously in memory .

Understanding of two-dimensional arrays:
insert image description here
This can also be confirmed二维数组在内存中是连续存储的 .


3. Array out of bounds


Array subscripts are limited in scope.

The subscript of the array starts from 0. If the input has n elements, the subscript of the last element is n-1.

Therefore, if the subscript of the array is less than 0, or greater than n-1, it means that the array is accessed out of bounds, and the access exceeds the legal space of the array.

The C language itself does not perform out-of-bounds checks for array subscripts, and the compiler does not necessarily report errors. But if the compiler does not report an error, it does not mean that the program is correct, so when programmers write code, it is best to do the out-of-bounds check by themselves.

#include <stdio.h>

int main()//错误演示
{
    
    
	int arr[5] = {
    
     1,2,3,4,5 };
	int i = 0;
	//越界
	for (i = 0; i <10; i++)
	{
    
    
		arr[i] = 0;//在这里赋值就会报错
	}

	return 0;
}

The error here is caused by the array out of bounds!
insert image description here
注意:二维数组的行和列也可能存在越界。


4. Arrays as function parameters


Often when we write code, we will pass an array as a parameter to a function , for example: I want to implement a bubble sort (here we will talk about the algorithm idea) function to sort an integer array .

4.1 The wrong design of the bubble sort function

If we design the function like this:

void BubbleSort(int arr[])
{
    
    
	int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	//冒泡排序的趟数
	for (i = 0; i < sz - 1; i++)
	{
    
    
		//冒泡排序的过程
		int j = 0;
		for (j = 0; j < sz - 1 - i; j++)
		{
    
    
			if (arr[j] > arr[j + 1])
			{
    
    
				//交换
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}

int main()
{
    
    
	int arr[] = {
    
     9,8,7,6,5,4,3,2,1,0 };
	BubbleSort(arr);

	return 0;
}

There will be a problem here. After debugging, you can see that sz == 1 inside the BubbleSort function! Isn't the entire array passed when
the array is used as a function parameter ?

4.2 What is the name of the array?

int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5 };
	printf("%p\n", arr);
	printf("%p\n", &arr[0]);
	printf("%d\n", *arr);
	printf("-----------------");
	printf("%p\n", arr + 1);
	printf("%p\n", &arr[0] + 1);
	printf("%d\n", *arr + 1);

	return 0;
}

Running Parse:
insert image description here
Conclusion:
数组名是数组首元素的地址。(有两个例外)

but:

int arr[10] = {
    
    0};
printf("%d\n", sizeof(arr));//当你这样输出结果发现,结果是:40?

Supplementary note:

  1. sizeof (array name), calculate the size of the entire array, put an array name inside sizeof, and the array name represents the entire array.
  2. &Array name, the address of the array is taken out. &Array name, the array name represents the entire array.

Except for the two cases 1 and 2, all array names represent the address of the first element of the array.

4.3 Correct Design of Bubble Sort Function

When an array is passed as a parameter , in fact, only the address of the first element of the array is passed .

So even if it is written in the form of an array in the function parameter part: int arr[], it still represents a pointer: int *arr.

So, the result of sizeof(arr) inside the function is 4.

So how should the function be designed (after the code is fully optimized)?

void BubbleSort(int arr[], int sz)//其实这里的int arr[]已经是指针了,相当于(int *arr[], int sz)
{
    
    
	int i = 0;
	//冒泡排序的趟数
	for (i = 0; i < sz - 1; i++)
	{
    
    
		//冒泡排序的过程
		int j = 0;
		int flag = 1;//假设已经有序

		for (j = 0; j < sz - 1 - i; j++)
		{
    
    
			if (arr[j] > arr[j + 1])
			{
    
    
				//交换
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
				flag = 0;
			}
		}

		if (1 == flag)
		{
    
    
			break;
		}
	}
}

void Print(int p[], int sz)
{
    
    
	int i = 0;
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", p[i]);
	}
}

int main()
{
    
    
	int arr[] = {
    
     9,8,7,6,5,4,3,2,1,0 };
	//不是传参的情况下,数组名单独放在fizeof内部的时候,
    //如:sizeof(arr),这里的arr表示整个数组,不是首元素的地址。
	int sz = sizeof(arr) / sizeof(arr[0]);

	//数组名在传递给函数的时候,会降级变成首元素的地址
	//数组传参---实际上传过去的是首元素的地址
	BubbleSort(arr, sz);//数组传参
	Print(arr, sz);
	return 0;
}

5. Application examples

  • Application example 1 of arrays: three chess
  • Array Application Example 2: Minesweeper Game

About this part, I will write a separate blog to teach you how to do it!
So I won’t introduce too much, I will post the link directly later, please look forward to it!

end of text

Guess you like

Origin blog.csdn.net/Cbiltps/article/details/120067835