C language: array (detailed explanation)

foreword

Array (Array) is an ordered sequence of elements. If a collection of finite variables of the same type is named, then this name is an array name. The individual variables that make up an array are called the components of the array, also called the elements of the array, and sometimes called subscript variables. The numerical numbers used to distinguish individual elements of an array are called subscripts. Array is a form in which several elements of the same type are organized in an orderly form for the convenience of processing in programming. These ordered collections of similar data elements are called arrays.

Therefore, arrays are used to store multipleA collection of data of the same type

Learn about arrays

array name

int a;
int b[10];

We can be sure that a is an integer variable, then b[10] is an array of integer types, and b meansarray name, then what is the type of the array name? In C language, the array name b is actually apointer constant, that is, the address of the first element of the array, the type depends on the type of the array element; of course, here, the array cannot be regarded as a pointer, the array has some characteristics completely different from the pointer, and the array is stored continuously in the memory. A pointer is just a scalar. So the array name represents the address of the first element of the array, however, there are two exceptions:sizeof(array name)and take address& array name, where sizeof (array name) represents the byte length of the entire array, not the byte length of the pointer;

int b[10];
printf(“%d”,sizeof(b));
Result: 40
Explanation: In an integer array, one element represents 4 bytes, and an array is 4*10=40 bytes

int b[10];
printf(“%p\n”,b);
printf(“%p\n”,&b);
printf(“%p\n”,b+1);
printf(“%p\n”,&b+1);
结果:
000000000061FDF0
000000000061FDF0
000000000061FDF4
000000000061FE18

insert image description here

subscript reference

In an array, we can find a specific element by referring to the subscript of the array element. The C language stipulates that array subscripts start from 0.
insert image description here
For example, if we want to find the fifth element, then we can directly refer to b[4]. In fact, in the C language, b[4] is called by dereferencing, that is, *(b+4), and the C language uses [] to express, which makes the expression more concise.
Look at the following code:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
    0};//数组的不完全初始化
    //计算数组的元素个数
    int sz = sizeof(arr)/sizeof(arr[0]);
 //对数组内容赋值,数组是使用下标来访问的,下标从0开始。所以:
 int i = 0;//做下标
 for(i=0; i<10; i++)
 {
    
    
 arr[i] = i;
 } 
 //输出数组的内容
 for(i=0; i<10; ++i)
 {
    
    
 printf("%d ", arr[i]);
 }
 return 0;
}

insert image description here
This is the following reference to the array. We can traverse the array through the for loop, and perform a series of operations such as assignment and printing.

Use of arrays

Array creation

Simply put, creating an array is adding [] to the array name, and the curly braces need to give a constant value. E.g.
int arr1[10];
Let's see,

int count = 10;
int arr2[count];

Is it possible here?

For array creation, before the C99 standard, a constant must be given in [], and variables cannot be used. The C99 standard supports the concept of variable-length arrays. The size of the array can be specified using variables, but the array cannot be initialized.

Array initialization

The meaning of array initialization and variable initialization is the same, both to give a reasonable initial value.
like:

int arr1[10] = {
    
    1,2,3};
int arr2[] = {
    
    1,2,3,4};
int arr3[5] = {
    
    12345}char arr4[3] = {
    
    'a',98, 'c'};
char arr5[] = {
    
    'a','b','c'};
char arr6[] = "abcdef";

It has been determined in arr1 that the array has 10 elements. We can use {} to assign values ​​to the array, but we can see that only 3 elements are assigned here. According to C, the unassigned ones default to 0. So the first three The first elements are assigned values ​​of 1, 2, and 3, and the others are 0.
In arr2, [] does not specify the specified number, but in the subsequent initialization of curly braces, 4 elements are assigned, so it is defaulted to arr2 There are 4 elements in , and the 4 elements are assigned respectively.
In arr3, values ​​are assigned from the first element to the last element.
arr4 is a character array, and we found that the second element is assigned a value of 98, so for characters, this 98 represents the 98th value in the ASCLL table, which is 'b'.
arr5 is equivalent to arr4
arr6 We found that it is initialized with a string of strings, which is reasonable for character arrays. Because one element represents one character. Therefore, for the following two arrays, they are actually equivalent.

char arr1[] = "abc";
char arr2[3] = {
    
    'a','b','c'};

Storage of arrays in memory

As we said above, arrays are stored contiguously in memory. Let's look at the following code:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
    0};
 int i = 0;
    int sz = sizeof(arr)/sizeof(arr[0]);
    
 for(i=0; i<sz; ++i)
 {
    
    
 printf("&arr[%d] = %p\n", i, &arr[i]);
 }
 return 0;
}

insert image description here
The array address is from low address to high address and the difference between adjacent addresses is 4, which is exactly one integer byte. So come toArrays are stored contiguously in memory
insert image description here

Two-dimensional array

If a one-dimensional array is a line, then a two-dimensional array is a plane.
Representation of a two-dimensional array:

int arr[3][4];
char arr[3][5];
double arr[2][4];

Let's use the integer two-dimensional array to illustrate, arr is a vector containing 3 elements, and each element itself is a vector containing 5 elements. In other words, arr is a one-dimensional array of one-dimensional arrays. That is to say, we can regard the constant in the first [] as the number of rows, and the constant in the second [] as the number of columns for representation.
insert image description here
But remember, this is just for the convenience of understanding for the user to see, it is a form of camouflage, the same is true in multidimensional arrays.

storage order

#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;
}

Result:
insert image description here
It can be seen that in a two-dimensional array, the array element memory is still stored continuously.
insert image description here

Initialization of two-dimensional array

int arr[3][4] = {1,2,3,4};

Explanation: There are three rows and four columns in the arr array. During initialization, only the first row is assigned and initialized, and the others default to 0.
insert image description here

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

Explanation: There are multiple curly braces in arr, and in the second layer of curly braces, it means to initialize an element of the row number.
insert image description here

int arr[][4] = { {2,3},{4,5}};

Explanation: If the two-dimensional array is initialized, the row can be omitted, but the column cannot be omitted.

subscript reference

Two-dimensional array subscript references are the same as one-dimensional arrays.
Look at the following code:

#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;
 	}
 }
 for(i=0; i<3; i++)
 {
    
    
 int j = 0;
 for(j=0; j<4; j++)
 {
    
    
 printf("%d ", arr[i][j]);
 }
 printf("\n");
 }
 return 0;
}

Result:
insert image description here
Explanation: The two-dimensional array starts from subscript 0 0 to the subscript 3 3 of the last element. Use two for loops to traverse nestedly to get the result.

array name

The array name of the two-dimensional array points to the first row, and +1 points to the second row;
insert image description here
insert image description here

Array out of bounds

When we have built an array and initialized it, it means that itsSpace memory is already determinedOf course, when accessing, ifWhen the subscript reference exceeds the scope, it is an out-of-bounds accessup. The C language itself does not check the out-of-bounds of the array subscript, and the compiler may not report an error, but the fact that the compiler does not report an error does not mean that the program is correct, so programmers must check when writing code.
like:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
    1,2,3,4,5,6,7,8,9,10};
    int i = 0;
    for(i=0; i<=10; i++)
   {
    
    
        printf("%d\n", arr[i]);//当i等于10的时候,越界访问了
   }
 return 0;
}

insert image description here
The last number here is a random number.
insert image description here

array as function parameter

From the above we know thatThe array name is a pointer, when the array name is passed as a parameter to a function it is actuallyThe address of the first element is passedIn the past, access to the data was then performed within the function by performing an indirection operation on that pointer. Since the array is stored continuously in the memory, when the formal parameter of the array is called in the function, the array can be called in the same way as the main function. However, just because the array name is a pointer, when using sizeof to calculate the size of the array in the function, errors often occur, because the address of the first element is called in the past at this time. So the solution is oftenWhen using an array as a parameter, a variable of the number of array elements will be brought.
For example: when calling the bubble sort function, the number will be calculated first in the function where the array is located, and then the parameters will be passed.
insert image description here

void bubble_sort(int arr[], int sz)//参数接收数组元素个数
{
    
    
  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};
    int sz = sizeof(arr)/sizeof(arr[0]);//先计算好个数
    bubble_sort(arr, sz);
    for(i=0; i<sz; i++)
   {
    
    
        printf("%d ", arr[i]);
   }
    return 0;
}

Result: 0 1 2 3 4 5 6 7 8 9

end

Well, the article ends here. Here are just some simple introductions to arrays, I hope it will be helpful to you.
insert image description here

Guess you like

Origin blog.csdn.net/m0_74068921/article/details/130764172