C language array study notes

What is an array?

An array is a kind of container. The elements in the array are arranged consecutively in the memory, and all the elements have the same data type. Once created, it cannot be resized. Each element of the array is a variable of the array type.

Array declaration

The array itself cannot be assigned, the assignment is the element of the array.

// 变量名称加中括号 
int number[10] ; 
// 集成初始化 
int number[] = {
    
    [1]=2,[2]=4} 
int number[] ={
    
    1,2,3,4}
int number[] ={
    
    [1] = 1,2,  [5]=5}

Subscript of array

The subscripts of the array use square brackets, such as a[1], starting from 0. The valid value is 0 to array size-1. The
compiler and runtime environment will not check whether the data subscript is out of range, whether it is reading or writing to the array element. Once the program is running, the out-of-bounds access of the array may cause problems and cause the program to crash. Therefore, C programmers have the responsibility to ensure that the program uses valid subscripts.

The length of the array

sizeof(x) can return the bytes of x, sizeof(array) is the byte occupied by the array, and sizeof(array[0]) is the byte of the first element of the array. Since each element of the array has the same type and the same type occupies the same bytes, the length of the array can
be calculated using sizeof(array)/sizeof(array[0]).

int a[]= {
    
    1,3,4} ;
printf("\d", sizeof(a)); 
printf("\d", sizeof(a[0]));
prinft("\d",sizeif(a)/sizeof(a[0]) );
>12
>4
>3

Iterate over the array

Generally, for is used to make the loop variable from i to <the length of the array, so that the maximum loop is just the largest effective subscript of the array.

for( i=0; i<length; i++}{
    
    } 

A common mistake is that the loop end condition is <= array length.

Two-dimensional array

A two-dimensional array can be understood as a matrix, and its declaration, assignment, and traversal just extend the one-dimensional array to two square brackets.

int number[3][5]int number[][2] ={
    
     
	{
    
    1,2,3},
	{
    
    2,4} 
	}

have to be aware of is:

The number of columns must be given, and the number of rows can be calculated by the compiler.
Each row has a separate {} separated by commas.
According to ancient traditions, the last comma can also exist.
Omission means zero padding,
positioning can also be used

The same applies to the generalized n-dimensional array (n>2)

Guess you like

Origin blog.csdn.net/weixin_43705953/article/details/114970572