- array
We have returned to the study of C language. Today we are going to further explain the array. I think you must have a little impression of the array when you finish the minesweeping and sanziqi games. I'm sorry to tell you first at that time. As an indispensable thing in any programming language, we must open a blog to explain it, Today's content is the focus of C language. I hope you don't jump or swallow. If you don't say much, let's start.
So what is an array? From the name, it is not difficult to find that an array is a group of numbers. It seems that a group of numbers are put together for others to use. This means that eight, nine and ten are inseparable. The so-called array is a group of numbers continuously stored in memory. The creation method is similar to that of variables. Type + name [];
1, One dimensional array
1. Creation and initialization of one-dimensional array.
An array is a collection of elements of the same type. How to create an array:
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 //type_t is the type of array, arr_name is the name you defined for the array, const_n is the number of initializations for the array //For example: //Code 1 int arr1[10]; //Code 2 int count = 10; int arr2[count];//When can arrays be created normally? //Code 3 char arr3[10]; float arr4[1]; double arr5[20];
Note: variables cannot be used to initialize the array, and constants can only be used in []. In the previous Minesweeper and Gobang games, you should note that the array defined in it is defined by #define, which is also possible. Because I have assigned initial values to the variables behind #define, it can be used as the number of array initialization.
After reading the initialization and definition of the array, let me ask you a question. Can I not initialize the value in []. If I don't put a constant in [], how large an array will it create for me? Will it report an error? Let me tell you: no error will be reported, which is in line with the syntax of C language. If the initial value is not given in the square brackets of the array, in order to make the C language more humanized, it means that the size of the array you define will change according to the number of subsequent elements, for example:
int arr1[10] = {1,2,3}; int arr2[] = {1,2,3,4};//Four elements int arr3[5] = {1,2,3,4,5}; char arr4[3] = {'a',98, 'c'}; char arr5[] = {'a','b','c'};//Three elements char arr6[] = "abcdef";//6 elements
However, it is recommended that you do not form the habit of defining the number of arrays without initialization. You should know how large the array you define is.
We now know int arr1[3]={1,2,3}; It defines an array with three int elements, char arr2[5]={"abcde"}; It defines an array of char type. There are five elements in the array. What if I give it this way: char arr3 [] = {a ',' B ',' C '}; Let's analyze. It's true that the array is of char type, and it's also true that there are three elements in it. But do you find that arr3 and arr2 are slightly different. One string is placed, and the other is placed one by one. What's the difference? The C language stipulates that when an array is defined, a \ 0 will be placed after the last element of the array by default. Then the corresponding value of this \ 0 in the ascci code is exactly 0. For example, when you calculate the number of elements in the array, it will automatically stop when you encounter \ 0 at the end of the count, so you can take \ 0 as a stop symbol, so you can run arr2 and arr3 on your own compiler to see how many elements there are in the two arrays, Arr2 has one more \ 0 than arr3, because arr3 is stored character by character and does not put \ 0. Therefore, the biggest difference between arr2 and arr3 is whether the programmer wants to put \ 0 in. If it doesn't matter, use arr2. If you don't want to put \ 0, use arr3.
2. Use of one-dimensional array
After we talked about the definition and initialization of arrays, how should arrays be used? Now let's write a piece of code to print 1 ~ 10.
#include <stdio.h> int main() { int arr[10] = {0};//Incomplete initialization of the array. At this time, all 10 elements in the arr array are 0 //Count the number of elements in the array int sz = sizeof(arr)/sizeof(arr[0]); //Assign a value to the contents of the array. The array is accessed by subscript, which starts from 0. So: int i = 0;//Subscript for(i=0; i<10; i++)//Write 10 here, okay? { arr[i] = i; } //Output the contents of the array for(i=0; i<10; ++i) { printf("%d ", arr[i]); } return 0; }
You may have some questions. Why i start with 0? It also uses left closed and right open, because the subscript of the array always starts from 0, which means that the subscript of the array of seven elements is 0 ~ 6, and the subscript of the array is always 1 less than our number. Therefore, by defining the value of i as 0 ~ 9, we can initialize the ten elements in the array as 0 ~ 9 respectively. Use the loop to print out the contents of arr.
Algorithm for the number of arrays: you can find this line in this Code: int sz = sizeof(arr)/sizeof(arr[0]); This is how to calculate the number of elements in the int array. Sizeof is an operator. We will talk about it later. Its function is to calculate the size. Putting the array name in sizeof means to calculate the size of the whole array, and then divide by the size of any element of the ARR array (take arr[0] here as an example). Because the array has ten elements, each element is of type int, Therefore, the size of the whole array is 10 * 4 = 40 bytes, and the size of an element is 4 bytes, so the number is 10, that is, the size of the array element. (Note: sizeof(arr)/sizeof(arr[0]) can only be used to calculate the number of elements of an int type array. If you want to calculate the number of elements of a char type array, use the strlen function.)
3. Storage of one-dimensional array in memory
We mentioned that arrays are stored continuously in memory, and each element is next to each other, so that we can get the elements we think of quickly and safely. How is it stored in memory? Next, let's study:
#include <stdio.h> int main() { int arr[10] = {0}; int i = 0; for(i=0; i<sizeof(arr)/sizeof(arr[0]); ++i) { printf("&arr[%d] = %p\n", i, &arr[i]); } return 0; }
%p is printed in the form of address, that is, the address of each element of the array in memory. What is the result after this code runs?
Here I want to tell you that addresses are stored in hexadecimal form, 0 ~ 9, A~F, so there are so many letters in the address. Let's look at 9C-A0 first. We know that C represents 12, plus four equals hexadecimal. According to hexadecimal, it is exactly one, and nine into one is exactly ten, that is, A, so we can find that arr[0] and arr[1] are four, and so on, Each element is also into 4, which is consistent with the fact that each element of the array we just talked about occupies four bytes in memory. Therefore, we found that the array is arranged in memory in the way of four bytes as an element, and the address of the elements is also increasing regularly.
2, Two dimensional array
1. Creation and initialization of two-dimensional array
After learning one-dimensional array, we have a general understanding of array. There is another array in C language, two-dimensional array. If one-dimensional array is a line, two-dimensional array is a face. Our previous minesweeping and three-dimensional chess games are also defined by two-dimensional array. It looks like a small grid. Because there are rows and columns, it is called two-dimensional, In terms of definition and initialization:
How to create a two-dimensional array? I don't think I need to talk about this problem. Everyone can think of how to create a one-dimensional array and a two-dimensional array. Length * width equals area. You can create it as long as you give the length and width. Yes, let's look at several:
int arr[3][4]; char arr[3][5]; double arr[2][4];
These two-dimensional arrays create a grid with behavior three columns as four, behavior three columns as five and behavior two columns as four in memory. Is it very simple? A classmate asked: since the one-dimensional array is very similar to the two-dimensional array, can you define it without writing the initial value? Determine how many elements there are according to the number I give. Note: rows can be omitted and columns cannot be omitted. That is to say, when we create a two-dimensional array, we must write columns, so that the compiler will automatically calculate rows according to the columns. I don't know why it can't be reversed. It may be a turtle, but it won't be omitted in general. I believe everyone is a diligent programmer.
//Here are some examples of creating a two-dimensional array int arr[3][4] = {1,2,3,4}; //Note: {} is added in {} to distinguish several lines. If it is not written, the compiler will automatically calculate according to the number of lines int arr[3][4] = {{1,2},{4,5}}; //This two-dimensional array initializes only two rows, //The elements of the entire third row and the fourth column of the first two rows are automatically initialized to 0 int arr[][4] = {{2,3},{4,5}}; //Here, the initial number of lines will be automatically: 2, because there are two {}, two elements in each row and two elements in each column, and the rest are 0
2. Use of two-dimensional array
The use method of two-dimensional array is the same as that of one-dimensional array. The subscript of its row and column also follows - 1, that is, the subscript of two-dimensional array also starts from subscript 0 to the subscript of element - 1. According to the code printed by one-dimensional array, we write a code for printing data in two-dimensional array:
#include <stdio.h> int main() { int arr[3][4] = {0}; int i = 0; for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { arr[i][j] = i*4+j;//Because it is a two-dimensional array, you must loop with a loop set } } for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { printf(%d ,arr[i][j]); } printf("\n");//Wrap after printing } return 0; }
Specifically, if you want to review how to use a two-dimensional array, you can go to the previous minesweeping and three-dimensional chess games, where there are special examples of the use of two-dimensional arrays.
3. Storage of two-dimensional array in memory
Well, as usual, let's also take a look at how two-dimensional arrays are stored in the memory address, but we can figure it out without guessing. It must also be stored in contact. After all, arrays are defined in this way:
#include <stdio.h> int main() { int arr[3][4]; int i = 0; for(i=0; i<3; i++) { int j = 0; for(j=0; j<4; j++) { printf("&arr[%d][%d] = %p\n", i, j,&arr[i][j]); } } return 0; }
The results are as follows:
According to the above method of calculating the address of one-dimensional array, calculate the two-dimensional array here, 48-4C. Because we also define the int type, 8 + 4 = 12. In hexadecimal, it is C, C+4=0, 0 + 4 = 4, which is just in line with our calculation, and the second line is calculated next to the first line, So we can safely remember this conclusion: two-dimensional arrays are also stored continuously in memory.
3, Array as function parameter
In the process of encapsulating functions, we cannot do without formal parameters and arguments, and we cannot do without the transfer of arrays. How do we transfer arrays as formal parameters? Taking bubble sort as an example, the function sorts an integer array. Then we will use this function as follows:
//Method 1: #include <stdio.h> void bubble_sort(int arr[]) { int sz = sizeof(arr)/sizeof(arr[0]);//Is that right? int i = 0; for(i=0; i<sz-1; i++) { int j = 0; for(j=0; j<sz-i-1; j++) { if(arr[j] > arr[j+1]) { int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } int main() { int arr[] = {3,1,7,5,8,9,0,2,4,6}; bubble_sort(arr);//Can I sort normally? for(i=0; i<sizeof(arr)/sizeof(arr[0]); i++) { printf("%d ", arr[i]); } return 0; }
You can run this code on your own compiler. This is an error code. What's the problem? You can use the debugging function of vs: ctrl+F11. When you enter the code, you can find that the sz we calculate is 1. Alas? I initialized 10. Why is sz 1? There must be something wrong with the calculation. Then we can trace back to the time when the array passed parameters. Is there only one element passed in? 4 / 4 = 1, so I guess only one element is passed in when passing parameters. How should we pass parameters? Before studying this problem, let's introduce the knowledge of array names:
What is the array name?
#include <stdio.h> int main() { int arr[10] = {1,2,3,4,5}; printf("%p\n", arr); printf("%p\n", &arr[0]); printf("%d\n", *arr); //Output results return 0; }
After running this code, you will find that the results printed on the first line are the same as those printed on the second line. The results printed on the third line are the value of the first element. We can conclude that the array name is the address of the first element of the array. But let's look back at this: why does sizeof(arr) calculate 40? There are two exceptions:
1. sizeof (array name), calculate the size of the whole array. sizeof has a separate array name inside, and the array name represents the whole array. 2. & array name, the address of the array is taken out& Array name, which represents the entire array.
Except for these two cases, the other array names are all the first element addresses. There is no doubt that the results in the first line and the second line of the code are the same.
After solving this problem, how to design bubble sorting?
//Method 2 void bubble_sort(int arr[], int sz)//Parameter number of array elements received { //... } int main() { int arr[] = {3,1,7,5,8,9,0,2,4,6}; int sz = sizeof(arr)/sizeof(arr[0]); bubble_sort(arr, sz);//Can I sort normally? for(i=0; i<sz; i++) { printf("%d ", arr[i]); } return 0; }
Compared with method 1 just now, we only need to calculate the number of array elements before passing them in when calling the bubble sorting function.
Well, that's the end of today's C language learning. Let's take a break and see you next time.