[C language] ☀ ⅸ comprehensive summary (detailed explanation + code demonstration + illustration + classic cases)

catalogue

1, What is an array?

2, Creation and initialization of one-dimensional array

Creation of one-dimensional array

Creation method

initialization

Incomplete initialization

Full initialization

Omit initialization of array length

Error demonstration

Initialization of character array

3, Use of one-dimensional arrays

Calculation of array length

Subscript of array

4, Storage of one-dimensional array in memory

5, Creation and initialization of two-dimensional array

Creation of two-dimensional array

Initialization of two-dimensional array

Incomplete initialization

Branch initialization

Omit row initialization

6, Use of arrays

7, Storage of two-dimensional array in memory

8, Array as an argument to a function

What is the array name

2 exceptions

Case: bubble sorting

analysis

code implementation

1, What is an array?

An array is a collection of elements of the same type, which are stored continuously in memory

Array is not the patent of C language. Java, C + +, c#, JavaScript, PHP and other programming languages also have arrays

C language array belongs to construction data type. An array can be decomposed into multiple array elements, which can be basic data types or construction types. Therefore, according to different types of array elements, arrays can be divided into numerical arrays, character arrays, pointer arrays, structure arrays and other categories.

In front ❤️ Organize 20000 words to take you into C language (detailed explanation + code demonstration + illustration) ❤️ (highly recommended collection!!!) This article has introduced the basic usage of arrays. Through this article, we will directly introduce arrays in an all-round way and take C language to a higher level

2, Creation and initialization of one-dimensional array

Creation of one-dimensional array

Creation method

```type_t arr_name[const_n];
//type_t is the element type of the index group
//const_n is a constant expression that specifies the size of the array```

Note that here const_ The position of N must be a constant expression and cannot be a variable

You can experience it through the following code

Code 1:

```int main()
{
int array[10];
}```

This code creates an array such as array. The array name is array, the number of array elements is 10, and the array element type is int

Code 2 (error demonstration):

```int main()
{
int count = 10;
int arr2[count];
}```

Operation results

Why?

This is because you cannot use variables to specify the size of an array when creating an array

Code 3:

```char arr3[10];
float arr4[1];
double arr5[20];```

This code is creating character array arr3,float type array and double type array respectively

initialization

The initialization of an array means that some reasonable initial values (initialization) are given to the contents of the array while creating the array

We just created an integer array in code 1, but there is nothing in the array. Now we can initialize it

Incomplete initialization

```int main()
{
//Create an array and initialize
int arr[10] = { 1,2,3,4,5 };     //Incomplete initialization. The remaining elements default to 0
int arr2[10] = {1,2,3,4,5,6,7,8,9,10};     //Full initialization
int arr3[10] = {0};
int arr4[] = {1,2,3,4};
}```

This arr array can hold 10 elements, but we only put the 5 elements of 1, 2, 3, 4 and 5 during initialization. The position of the remaining 5 elements is 0 by default. We can take a look through the monitor

You can see that the inches in the array arr are 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0

Full initialization

Code 1:

```int main()
{
//Create an array and initialize
int arr2[10] = {1,2,3,4,5,6,7,8,9,10};     //Full initialization
}```

Then look at the elements in the arr2 array in the monitor

Code 2

```int main()
{
//Create an array and initialize
int arr3[10] = {0};
}```

Omit initialization of array length

```int main()
{
//Create an array and initialize
int arr4[] = {1,2,3,4};
}```

The array arr4 is initialized without specifying the length of the array. It is often used in daily code. Although the array length is not written in [], you initialize several elements. The length of the array is certain. If you initialize four elements later, it is equivalent to 4 in []. It is the same when you write and not write

However, it should be noted that the writing method of arr4 must be initialized at the time of creation, otherwise it is wrong. The compiler cannot calculate the length of the array

Error demonstration

```int main()
{
int arr4[];
}```

Initialization of character array

```int main()
{
int ch1[] = "abcde";
int ch2[] = { 'a','b','c','d','e' };
int ch3[3] = {'a','b','33'};
}
```

These two initialization methods will be used. ch1 is written in the form of a string, while ch2 is directly a single character. What is the difference between the two initialization methods?

ch1 is initialized with a string, and there must be '\ 0' as the end flag

ch2 is followed by a single character without '\ 0

Monitor observation:

We can further understand it through the following question:

```#include <stdio.h>
int main()
{
char ch1[] = "abcde";
char ch2[] = { 'a','b','c','d','e' };
printf("%d\n", sizeof(ch1));
printf("%d\n", sizeof(ch2));
printf("%d\n", strlen(ch1));
printf("%d\n", strlen(ch2));
return 0;
}
```

Let's first think about the execution result of this code?

analysis:

Ch1 and ch2 are arrays of character types, and each element occupies one byte. In ch1, a string is stored, with 5 characters and '\ 0', so the value of sizeof(ch1) should be 6, the value of strlen(ch1) should be 5, the value of sizeof(ch2) should be 5, and there is no end flag '\ 0' after ch2, so strlen(ch2) should be a random value

Operation results:

Here 21 is a random value

3, Use of one-dimensional arrays

For the use of arrays, we introduced an operator: [], the subscript reference operator. It's actually an array access operator

Calculation of array length

Here is a method to calculate the number of array elements (array length)

Array length = = total array size / array element size

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

Operation results:

Subscript of array

We usually access the array by subscript. It should be noted that the subscript of the array does not start from 1, but from 0. Each element in the array corresponds to a subscript

Through the following code, let's experience how to use an array (print the elements of the array)

```#include <stdio.h>
int main()
{
int i = 0;
int arr[] = { 0 };
int sz = sizeof(arr) / sizeof(arr[0]);

//Print elements of an array
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}```

Operation results:

4, Storage of one-dimensional array in memory

How are one-dimensional arrays stored in memory? We can print out the address of each element in the array, as shown in the following code:

```#include <stdio.h>
int main()
{
int i = 0;
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);

//Print the element address of the array
for (i = 0; i < sz; i++)
{
printf("%p ", &arr[i]);
}
return 0;
}```

Operation results:

analysis:

The size of each element of the integer array is 4 bytes. We can see from the running results that each address has a difference of 4. Therefore, we can know that the elements of the array are stored continuously in memory, and the address also increases from low to high with the increase of the array subscript

5, Creation and initialization of two-dimensional array

Creation of two-dimensional array

```//Array creation
int arr1[3][4];
```

arr1 array is an array named arr1. Each element in the array is an integer, as shown in the following figure: a two-dimensional array with three rows and four columns

Initialization of two-dimensional array

Incomplete initialization

The code is as follows

```int main()
{
int arr[3][4] = { 1,2,3,4,5 };    //Incomplete initialization
}```

This array has 3 rows and 4 columns. It can store 12 elements, but only 4 are initialized. The other elements will be initialized to 0 by default. We can take a look through the monitor

Branch initialization

What if you want to put 1 and 2 on the first line, 3 and 4 on the second line, and 5 on the third line? The following code:

```int main()
{
int arr[3][4] = { { 1,2 },{ 3,4 },{ 5 } };    //Incomplete initialization
}```

Monitor observation:

Omit row initialization

```int main()
{
int arr[][4] = { { 1,2 },{ 3,4 },{ 5 } };    //Incomplete initialization
}```

There is no problem in omitting the number of rows 3 directly here, but it should be noted that the number of columns must not be omitted

Monitor observation:

6, Use of arrays

First, let's look at the two-dimensional array above

The following code (prints each element in the array):

```int main()
{
int arr[][4] = { { 1,2 },{ 3,4 },{ 5 } };
int i = 0;    //that 's ok
int j = 0;     //column
for (i = 0; i < 3; i++)     //Control line
{
for (j = 0; j < 4; j++)     //Control column
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}```

Operation results

7, Storage of two-dimensional array in memory

We saw that a one bit array is stored continuously in memory. What about a two-dimensional array?

Let's print out the address of each element of the array

```#include <stdio.h>
int main()
{
int arr[][4] = { { 1,2 },{ 3,4 },{ 5 } };
int i = 0;    //that 's ok
int j = 0;     //column
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
printf("%p\n", &arr[i][j]);
}
}
return 0;
}```

Operation results

The size of each element of the integer two-dimensional array is also 4. It can be seen that the address of each element of the two-dimensional array is continuous, and the two-dimensional array is also stored continuously in memory

Therefore, although our two-dimensional number group diagram is drawn with 3 rows and 4 columns, it is only for ease of understanding. We should know that its real storage in memory is still continuous, as shown in the following figure

We can understand the above two-dimensional array as three one-dimensional arrays, and the array names of the three one-dimensional arrays are: arr1[0], arr1[1], arr1[2]

8, Array as an argument to a function

What is the array name

The array name is actually the address of the first element of the array

We can take a look at it through the following code:

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

Operation results:

analysis:

It can be seen that by dereferencing the array name, the first element of the array is printed, and the result of directly printing the array name is the same as that of printing the address of the first element of the array, which shows that the array name is the address of the first element of the array

2 exceptions

1. Sizeof (array name) -- the array name here represents the entire array
2. &Array name ---- it also represents the whole array, and the address of the whole array is taken out

Case: bubble sorting

Now we have an array, and we want to sort its elements

Run sort

analysis

Here, a dynamic graph on the Internet is used to clearly show the core idea of bubble sorting

This figure clearly shows the bubble sorting method. Each bubble sorting is traversed from front to back. Adjacent elements are compared, and those that do not meet the conditions are exchanged. If there are 10 elements in the array, 9 bubble sorting is required, and 10-1-times pairs of elements are compared each time

Bubble sort per trip

A total of 10 elements require 9

code implementation

```#include <stdio.h>
void bubble_sort(int arr[],int sz)
{
int i = 0;   //Used to indicate the number of bubbling trips
for (i = 0; i < sz - 1; i++)
{
int j = 0;    //Subscript used to represent an array
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void print_arr(int arr[], int sz)     //Define this function to print the array
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);    //Calculate the number of array elements
bubble_sort(arr, sz);
print_arr(arr, sz);
return 0;
}
```

--------------------------------------------------------------------------------

-------------------------Partial completion of C language array-----------------------------

About C language, each knowledge point will be introduced in more detail in a separate blog

Welcome to pay attention!!!

Learn and communicate together!!!

Let's finish the programming!!!

--------------It's not easy to organize. Please support the third company------------------

Tags: C C++ Programming

Posted by Griven on Tue, 21 Sep 2021 06:50:03 +0530