A simple understanding of arrays in C language

array

Introduction to Arrays

An array is a series of elements of the same data type. When using an array, you need to declare the array first. According to this information, the compiler can successfully create the array.

Array declaration example

float arr[30];//包含30个float类型的元素的集合
char arr1[20];//包含20个char类型元素的集合
int arr2[10];//包含10个int类型元素的集合

But it can't be declared like this

int arr[];//错误

Format of array declaration

type name[ ] ;

First the type of the array, then the name of the array, "[ ]" is used to indicate that the name is an array, and "[ ]" is the number of elements in the array

initialize the array

When an array is created, giving some initial values ​​is called initialization

Generally, the array is initialized at the beginning of the program.

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

Here an array arr with 3 elements is created, {1,2,3} assigns 1 to the first element of the array, 2 to the second element of the array, and 3 to the second element of the array. gives the third element of the array. The comma between "1,2,3" is used to separate the values ​​to ensure that there is no error when assigning.

There are other initialization methods

char ch[] = "abc";
char ch1 = {
    
    'a','b','c'};
int arr[] = {
    
    1,2,3};//这个数组只有三个元素

Fully initialized:

There are several element positions to give the value of several elements

int arr[10] = {
    
    1,2,3,4,5,6,7,8,9,10};

When the number of assignments exceeds the number of elements, an error is reported:
too many initializers

int arr[3] = {
    
    1,2,3,4,}//初识值多了,这样的写法是错误的

Incomplete initialization:

int arr[10] = {
    
    0};//全部都初始化为0
int arr[10] = {
    
    1,2,3};//后面的几个元素都被默认初始化为0

String and character initialization

When the string is initialized: '\0'


int arr1[] = "abc";//a,b,c,\0————有四个元素,数组大小是四个字节
printf("%d",sizeeof(arr));//4
printf("%d",strlen(arr));//3__遇到\0就停止了,计算\0前面的

There is no character when initializing: '\0'

int arr[] = {
    
    'a','b','c'};//a,b,c————有三个元素,数组大小是三个字节
printf("%d",sizeeof(arr));//3
printf("%d",strlen(arr));//随机值,遇不到\0

Array storage and subscripting

When creating an array, a contiguous space is allocated in memory, so the addresses of the n elements of the array are contiguous:

For such an array arr[3] = {1,2,3};

#include<stdio.h>
int main()
{
    
    
	int arr[3] = {
    
     1,2,3 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	printf("%d", sz);
	return 0;
}

insert image description here

Then how can we see that the different elements in the array are used, here we need to use the subscript reference operator " [ ]",

We create a new array and print out its different elements

#include<stdio.h>
int main()
{
    
    
	int arr[3] = {
    
     100,200,300 };
	
	printf("arr[0] =%d\n", arr[0]);
	printf("arr[1] =%d\n", arr[1]);
	printf("arr[2] =%d\n", arr[2]);

	return 0;
}

insert image description here

We know that the data of 100 is stored in the first element of the array, but the subscript of the first element of the array is 0, so when we print the value of arr[0], 100 will appear. And so on, the index of the second element of the array is 1, the index of the third element is 2...

It is important to know which array element corresponds to which subscript

Input and output of array elements

When we process a lot of data, we will use arrays, and when there is a lot of data, it will take a lot of time to input and output in the following way

For example, if we need to input 100 values ​​to go out in the array, then we need to input 100 scanf functions, and do we need to type 100 printf functions when outputting?

#include<stdio.h>
int main()
{
    
    
int arr[100] = {
    
    0};
    //输入
    scanf("%d",&arr[0]);
    scanf("%d",&arr[1]);
    scanf("%d",&arr[2]);
    ...
	scanf("%d",&arr[99]);
    //输出
    printf("%d",arr[0]);
    printf("%d",arr[1]);
    printf("%d",arr[2]);
    ...
    printf("%d",arr[99]);
return 0;
}

Obviously this is very troublesome, and when we need to input a lot of data of the same type and print a series of data of the same type, we will think of looping

Yes, the loop can solve the above problem very easily

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

The above loop can quickly solve the problem of input and output, but sometimes the array we encounter is like this

int arr[] = {
    
    1,2,3,4,5,6,7,8,9,1,2,3};

Such array initialization is legal, but when looping, we need to know when to terminate the loop. When executing the array that prints 100 elements above, we clearly know that there are 100 elements, so loop within the condition of i<100, But at present, in this array, we can't determine how many elements there are by pressing hard. Why can we use such an expression to calculate the number of elements in the array?

int sz = sizeof(array)/sizeof(array[0]);

//这里相当于创建了一个整形变量,来储存表达式sizeof(array)/sizeof(array[0])的结果
/*对于等号后面的表达式:sizeof(),
如果括号里面的是单个数组名,那么sizeof(array)计算的就是整个array数组的大小(单位字节)
如果括号里面的是单个数组元素,那么计算的四则偶分(array[0])计算的就是这个元素的大小(单位字节)
*/

Then the following is the code to print the array of int arr[] = {1,2,3,4,5,6,7,8,9,1,2,3}

#include<stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,1,2,3 };
	int sz = sizeof(arr) / sizeof(arr[0]);//这里计算出了数组元素的个数
	int i = 0;
	for (i = 0; i < sz; i++)
	{
    
    
		printf("arr[%d] = %d\n", i,arr[i]);
	}
	return 0;
}

insert image description here

array out of bounds

Arrays are bounded

When using the array, you need to be careful not to exceed the subscript of the array, that is, if the array you create is arr[20], then when the subscript is called, use the subscript of 0-19, otherwise the array will be out of bounds

We know that the array uses a continuous space when it is created, so the addresses of several elements of the array are continuous. When the array is out of bounds,

Or take this example:

int arr[20]= {
    
    0};
//当我们在打印的时后错误使用了:
printf("%d",arr[-1]);
printf("%d",arr[20]);
//这两种下标都超出了数组的边界
//这时arr[-1]的地址在数组地址前面
//arr[20]的地址在数组地址后面


//如果arr[-1]的地址上没有赋值,那么打印出来的就是一堆乱码,arr[20]也一样
    
    

Compilers generally do not check for problems such as array out-of-bounds

Creation and initialization of two-dimensional arrays

Creation of a two-dimensional array

The creation of two-dimensional arrays has many similarities with one-dimensional arrays: such as array types, array names, and the [ ] operator.

There are also different places:

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

A two-dimensional array is created with an additional [ ] symbol, which is equivalent to creating an additional dimension.

The total number of elements in a two-dimensional array is equal to the product of the two numbers in parentheses

int arr[3][4];//有 12 个元素
int arr[5][5];//有 25 个元素

Such an array can also be understood as: arr is a large set, the following contains three small sets arr[0], arr[1], arr[2], each set facet includes several smaller gather

insert image description here

Initialization of a two-dimensional array

There are many ways to initialize two-dimensional arrays, and different methods have different initialization effects.

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

insert image description here

It can be seen that this initialization is to assign the first few elements of arr[0], the first few elements of arr[1], the first few elements of arr[3], and the rest of the elements are assigned to 0 ;

two-dimensional array storage

Two-dimensional arrays are very similar to one-dimensional arrays in terms of storage, both use continuous space, but the "continuous" stored in two-dimensional arrays is the element address of a small set of values ​​followed by the first of the next small set. element address

insert image description here

This picture shows that the address of
arr[0][4] is: 0x00AFF834 The address of
arr[1][0] is: 0x00AFF838 The
two addresses are consecutive, which confirms the above conclusion.

Two-dimensional array rows can be omitted, but columns cannot be omitted

int arr[2][3] ={
    
    1,2,3,4,5,6}//一个含有六个元素的数组
int arr[][3] = {
    
    1,2,3,4,5,6}//与上面的结果相同
int arr[2][] = {
    
    1,2,3,4,5,6}
/*第三个是错误的,会造成歧义,系统只知道要创建两个六个空间分两部分使用,
但是不知道每一个空间分配多少个元素,造成报错*/

arrays and functions

Array elements as arguments to functions

Array elements can be used as actual parameters of functions, but cannot be used as formal parameters (formal parameters are temporarily allocated space by unit, and a unit will not be allocated for an array element alone). When passing, just pass the value of the array element to the formal parameter, here we use an example to illustrate the "value passing" of the array element as a function argument

Example: Enter ten numbers in an array and print the largest of the ten numbers

#include<stdio.h>
int MAX(int x,int y)
{
    
    
	return x > y ? x : y;
}//比较函数
int main()
{
    
    

	int arr[10] = {
    
     0 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		scanf("%d", &arr[i]);
	}//读取十个数
	int max = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		max = MAX(arr[i], max);
            //arr[i]作为函数实参,将arr[i]的值传给了形参x

	}//作比较 
    
	printf("max = %d\n", max);
    
    for (i = 0; i < 10; i++)
	{
    
    
		printf("arr[%d] = %d\n", i, arr[i]);

	}
	return 0;
}
//输入1 2 10 9 8 7 6 5 4 3  
//打印的是:max = 10;

It can be seen that the value of each array element does not change after being used as a function parameter. It can be confirmed that when the array element is used as an actual parameter, only its own value is passed to the formal parameter.

array name as function parameter

Different from the brush group elements, the array name can be used not only as the actual parameter of the function, but also as the formal parameter of the function.

When using the array name as the actual parameter of the function, the address of the first element is passed. In many cases, the array name represents the address of the first element.

Similarly, here is an example to illustrate the case where the array name is used as a parameter

#include<stdio.h>

int average(int arr[])
    //实参对应的形参指定和实参一样的类型
    //形参的数组可以不指定大小
    //
{
    
    
	int i = 0;
	int sum = arr[0];
	for (i = 1; i < 10; i++)
	{
    
    
		sum += arr[i];
	}
	return sum / 10;
}
int main()
{
    
    
	int score[10] = {
    
     0 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		scanf("%d", &score[i]);
	}
	int aver = average(score);//函数名做实参
	printf(" %d\n", aver);
	return 0;
}

It can be considered that the address of the first element of the formal parameter group is the same as the address of the first element of the real parameter group, they communicate and occupy the same unit, and the real parameter group and the corresponding formal parameter group have the same value.

Guess you like

Origin blog.csdn.net/cainiaochufa2021/article/details/121307198