--The difficulty of things is far less than the fear of things!
In this chapter, let's talk about arrays, which are actually ordered collections of identical variables . Specifically, please refer to the following figure:
As you can see from the above figure, the array stores elements in a continuous memory space , and the number of array elements can be specified explicitly or implicitly
- int a[5] = {1,2}; //Display that the specified array element is 5, and the uninitialized element defaults to 0, that is, the value of a[2]~a[4] is 0
- int b[] = {1,2}; //Implicitly specified, the number of arrays is identified by the compiler itself, where the identification result is 2
For the array name and array address, taking int a[5] as an example, the relationship is as follows:
- The array name a represents the address of the first element of the array (ie &a[0] == a)
- The address of the array needs to be obtained by taking the address character & (that is, the address of the array is &a)
- The address of the first element of the array is the same as the array address value , but the concept is different (that is, a and &a are numerically the same, but a represents the address of a[0], but &a represents the address of the array in memory)
For the use of arrays, you need to pay attention to the following points:
- The array name can be regarded as a constant pointer , which determines that the array name can only be used as an rvalue in the expression
- The array name "points" to the starting address of the first element of the array in memory
- The array name does not contain the length information of the array
- The array name cannot be treated as a constant pointer only in the following cases
- The array name is used as the parameter of the sizeof operator (sizeof(array) gets the space occupied by the entire array in memory)
- array name as argument to & operator
Summarize:
- An array is a contiguous piece of memory space
- The address of the array is the same as the address value of the first element of the array, and the meaning is different
-Array names are treated as constant pointers in most cases
- The array name is not a pointer and cannot be treated the same as a pointer