I've learned the basic part of c language. Let's have an in-depth understanding of it
array
1. One dimensional array
What are arrays for? Like the variable we mentioned earlier, it is used to store data. How is it different from variable storage data?
Obviously, a variable can only save one piece of data, which is more convenient to use when the amount of program data is small. However, for large-scale data, simple variables are a little thin. To deal with large-scale data, we need more powerful data types to condense many variables together to form an array.
In short, an array is a collection of data of the same type. The following is a simple array defined and initialized:
int a[5]={10,20}; //Partial initialization int a[5]={[4]=20,[2]=10} //Specify initialization float c=['A']; int m,g[10]; //If array and variable are of the same type, they can be defined together
Let's deepen the basic operation of arrays through a comprehensive small case.
//Requirements: the user inputs 5 integers, saves them to the array, and prints all elements in reverse order. The procedure is as follows: #include<stdio.h> int main(){ int i,a[5]; printf("Please enter 5 integers:\n"); for(i=0;i<5;++i) scanf("%d",&a[i]); //Take i as the value in the following table and assign an initial value to the array element printf("Print array elements in reverse order:\n"); for(i=4;i>=0;--i) printf("%d",a[i]); //Print the array element value with i as the subscript value return 0; }
Finally, for array operations, we must remember not to access beyond the bounds, so as not to access the memory area outside the array.
2. Array as function parameter
C language allows the array to be used as the parameter of the function, that is, the array name can be passed as the argument of the function. You can add square brackets after the parameter name to indicate that the parameter is an array type. The following is a function PArray with array as parameter:
void PArray(int arr[]){ for(int i=0;i<5;i++){ arr[i]*=10; printf("%d ",arr[i]); } }
3. Character array
In C language, almost all data types can be defined as arrays. Because arrays can be used to store strings, character arrays are widely used in C language.
Although there is no string data type in C language, its application is very common, such as our first program "hello world". Notice that it is a sequence of characters enclosed in double quotes. In addition, a string has another important feature: the string must end with an empty character (represented by the escape character '\ 0'). Even string constants implicitly have this null character. For example:
"abc" //This string is composed of four characters, namely characters a, b, c and null characters. Its size is 4 bytes
So, how can we store the "abc" string in an array?
//Method 1: character storage char str[4]={'a','b','c','\0'}; //All initialization mode char str[4]={'a','b','c'}; //Since the ASCII code value of null character is 0, partial initialization can also be adopted //Method 2: string storage char str[4]="abc"; //In actual programming, in order to avoid the problem of insufficient array length, we usually recommend the following method for assignment: char str[]="abc";
After looking at the above method 2, we may be wondering how to get the length of a string, right?
For a string, it has the concept of length in addition to size. Let's make a simple distinction here:
The size of the string refers to the number of bytes of memory occupied by the string, which is calculated by the sizeof() library function, while the length of the string refers to the number of valid characters in the string, which is calculated by the strlen() library function. The so-called valid characters are characters other than the empty characters as the end mark.
4. Two dimensional array
Ah, five rings, you have one ring less than six rings ~, as the name suggests, a two-dimensional array is one more dimension on the basis of a one-dimensional array, simply one more "[]".
As for the initialization of two-dimensional array, it is similar to the initialization of one-dimensional array. The following is a downlink initialization method:
float score[3][3]={ {88.5,86.5,96}, //Line 1 {88.5,86.5,96}, //Line 2 {88.5,86.5,96}, //Line 3 }
As mentioned earlier, one-dimensional arrays can be used as function parameters. By analogy, two-dimensional arrays can also be used as parameters for function calls. Similar to the one-dimensional array as a function parameter, the parameter name needs to be followed by a pair of brackets. The two-dimensional array needs two pairs of brackets. The first pair of brackets is used to represent the size of the first dimension, and its value can be omitted, that is, the form of empty brackets is used; The second pair of brackets is used to indicate the size of the second dimension, and its value cannot be omitted, that is, the size of the second dimension must be indicated. The following is a function example for printing all elements of a two-dimensional array:
void printScore(float s[][4],int len){ for(int i=0;i<len;i++){ for(int j=0;j<4;j++) printf("%6.2f",s[i][j]); //Print in a format of 6 characters wide with 2 decimal places printf("\n"); //Wrap after printing a line of elements } }
Finally, we can use this idea to understand the array in C language:
An array composed of ordinary elements (variables) is a one-dimensional array, that is, a one-dimensional array is an array of ordinary elements (variables).
An array composed of one-dimensional arrays is a two-dimensional array, that is, a two-dimensional array is an array of one-dimensional arrays.
An array composed of two-dimensional arrays is a three-dimensional array, that is, a three-dimensional array is an array of two-dimensional arrays.
.......
It will be easier to understand the nesting of arrays and the relationship between pointers and arrays ~~
Review in practice (summary)
Understanding and mastering arrays will lay a solid foundation for later knowledge expansion. The real mastery of arrays can not rely on theoretical knowledge alone, but more practice. The more classic topics are matrix transpose and bubble sorting. Here is a review of the knowledge of arrays with the implementation of a classic bubble sorting algorithm.
Write a program to save 10 random integers of 1 ~ 100 in the array, sort the array in ascending order, and print out the sorted array elements. The code is as follows:
#include <stdio.h> #include <stdlib.h> #include <time.h> //Bubble sorting void bubble(int a[], int len) { int i, j, tmp; //1. The outer loop will execute len - 1 times, indicating that a total of len - 1 rounds of comparison process are carried out for (i = 0; i < len - 1; ++i) { /*The inner loop is used to complete each round of comparison. It starts with the first element in the sequence to be sorted and compares it with the subsequent elements one by one. In addition, with the increasing value of i in the outer loop, the expression "len - 1-i" will gradually reduce the execution times of the inner loop, which is equivalent to excluding the maximum element after each round from the sequence to be sorted*/ for (j = 0; j < len - 1 - i; ++j) { if (a[j]> a[j + 1]) //Check whether the previous element is larger than the latter / / if so, exchange the values of the two elements { tmp = a[j]; //Assign the previous element value to tmp a[j] = a[j + 1];//Assign the value of the latter element to the previous element a[j + 1] = tmp;// Assign the tmp value to the next element } } } } int main() { int i, arr[10]; //Set random number seed srand(time(NULL)); //Get 10 random numbers by loop and save them to array arr for (i = 0; i < 10; ++i) arr[i] = rand() % 100 + 1; //Call the bubble function for bubble sorting. Parameter 1 is array arr and parameter 2 is the length of array arr bubble(arr, 10); //Print out the value of each element in the sorted array for (i = 0; i < 10; ++i) printf("%d ", arr[i]); return 0; }
Well, after the above review, do you have a deeper impression of arrays in C language?