C language - array [detailed]

1. Creation and initialization of one-dimensional array

1.1 Array creation

An array is a collection of elements of the same type.
An instance of array creation:

//代码1
int arr1[10];
//代码2
int count = 10;
int arr2[count];//数组时候可以正常创建?
//代码3
char arr3[10];
float arr4[1];
double arr5[20];

Note: To create an array, before the C99 standard, one should be given in []constantOnly then, 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.

1.2 Array initialization

Array initialization refers to giving some reasonable initial values ​​(initialization) to the contents of the array while creating the array.
Code example:

int arr1[10] = {
    
    1,2,3};//不完全初始化,剩余的默认初始化为0
int arr2[] = {
    
    1,2,3,4};//不给定大小数组会根据初始化的内容来确定大小
int arr3[5] = {
    
    12345}//完全初始化
char arr4[3] = {
    
    'a',98, 'c'};
char arr5[] = {
    
    'a','b','c'};
char arr6[] = "abc";

The actual operation explains the difference between char arr5[] and char arr6[]
insert image description here

1.3 Use of one-dimensional arrays

For the use of arrays, we introduced an operator before: [] , the subscript reference operator. It is actually an operator for array access.
Let's look at the 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;
}

Summarize:

  1. Arrays are accessed using subscripts, which start at 0.
  2. The size of the array can be calculated.
  3. Arrays are also typed

int sz = sizeof(arr)/sizeof(arr[0]);//calculate the size of the array

1.4 Storage of one-dimensional arrays in memory

Print the address to see how it is stored in the array
Look at the 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;
}

Running results:
insert image description here
Carefully observe the output results, we know that with the increase of the array subscript, the address of the element is also increasing regularly. There is a difference of four bytes between every two adjacent addresses.
It can be concluded from this that the array is stored continuously in memory.
insert image description here
Code two:

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int* p = &arr[0];
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%p == %p\n", p + i, &arr[i]);
	}
	return 0;
}

Running result:
insert image description here
If p is the starting position, then p+i is gradually searched by increasing from the starting position one by one, as shown in the figure below,
insert image description here
then, if we want to print out all the elements in the array, we can dereference the pointer to inquire

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int* p = &arr[0];
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", *(p + i));
	}
	return 0;
}

2. Creation and initialization of two-dimensional array

2.1 Creation of two-dimensional array

//数组创建
//[行][列]
int arr[3][4];
char arr[3][5];
double arr[2][4];

2.2 Initialization of two-dimensional array

#include <stdio.h>
int main()
{
int arr1[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
printf(“%d\n”, arr1[1][2]);
return 0;
}

//数组初始化
int arr[3][4] = {
    
    1,2,3,4,5,6,7,8,9,10,11,12};//完全初始化
int arr[3][4] = {
    
    {
    
    1,2},{
    
    4,5}};//不完全初始化
//{1,2}放第一行,{4,5}放第二行,以此类推
int arr[][4] = {
    
    {
    
    2,3},{
    
    4,5}};//二维数组如果有初始化,行可以省略,列不能省略

2.3 Use of two-dimensional arrays

The use of two-dimensional arrays is also through subscripts.
Look at the code:

#include <stdio.h>
int main()
{
    
    
	int arr1[3][4] = {
    
     1,2,3,4,5,6,7,8,9,10,11,12 };
	printf("%d\n", arr1[1][2]);
	return 0;
}

The row and column of the subscript of the two-dimensional array also start from 0, find the subscript of the row and column to find the element
Access each element of the two-dimensional
array Code demonstration:

#include <stdio.h>
int main()
{
    
    
	int arr1[3][4] = {
    
     1,2,3,4,5,6,7,8,9,10,11,12 };
	int i = 0;
		for (i = 0; i < 3; i++)//0 1 2
		{
    
    
			int j = 0;
			for (j = 0; j < 4; j++)
			{
    
    
				printf("%2d ", arr1[i][j]);
				//%2打印两位右对齐,%-2d左对齐
			}
			printf("\n");
		}
	
		return 0;
}

2.4 Storage of two-dimensional arrays in memory

Like 1D array, here we try to print each element of 2D array.

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

Print the result:
insert image description here
We can analyze the result, in fact, the two-dimensional array is also stored continuously in the memory.
insert image description here
If each row of a two-dimensional array is regarded as a one-dimensional array, then the one-dimensional array of each row also has an array name.
arr[0] is the array name of the first row, and arr[1] is the array name of the second row. , and so on

3. Array out of bounds

Array subscripts are limited in scope.
The next specification of the array is from0At the beginning, if the array has n elements, the subscript of the last element isn-1.
Therefore, if the subscript of the array is less than 0, or greater than n-1, it means that the array is accessed out of bounds, and the access exceeds the legal space of the array.
The C language itself does not perform out-of-bounds checks for array subscripts, and the compiler may not necessarily report an error , but the fact that the compiler does not report an error does not mean that the program is correct,
so when programmers write code, it is best toDo your own out-of-bounds checks
Code description:

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

The running result is wrong, because the subscript access is out of bounds, but the compiler does not report an error.
insert image description here
The rows and columns of the two-dimensional array may also be out of bounds.

4. Arrays as function arguments

Often when we write code, we pass an array as a parameter to a function, for example: I want to implement a bubble sort, and the function sorts an integer array.

4.1 Bubble sort

Bubble sorting idea: Compare two adjacent elements, move the larger number backward, and move the smaller number forward
Specific graphic explanation:
A bubble sort, find and fix the largest number on the right (bubble bubble sort in ascending order)
insert image description here

What is the name of the array?
Look at the code:

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5 };
	printf("%p\n", arr);
	printf("%p\n", &arr[0]);
	printf("%d\n", *arr);
	//输出结果
	return 0;
}

Running results
insert image description here
conclusion:

The array name is the address of the first element of the array. (with two exceptions)

  1. sizeof (array name), if the array name is placed inside sizeof alone, the array name here represents the entire array, and the calculation is the size of the entire array
    For example:
    insert image description here
    the output result of this code is 40
  1. &Array name, the array name here represents the entire array, and the address of the entire array is taken out
    In addition, all the array names encountered are the addresses of the first element of the array

Sort code:

#include <stdio.h>
void bubble_sort(int arr[], int sz)
    //因为数组传参传的是地址,所以int arr[] 表示的依然是一个指针: int *arr 
{
    
    
	int i = 0;

	//冒泡排序的趟数
	for (i = 0; i < sz - 1; i++)
	{
    
    
		//一趟冒泡排序的过程
		int j = 0;
		for (j = 0; j < sz - 1 - i; 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,5,9,2,4,7,6,8,0 };
	//排序 - 升序
	//冒泡排序
	int sz = sizeof(arr) / sizeof(arr[0]);

	bubble_sort(arr, sz);//arr是数组首元素的地址
	//只传数组不传元素个数进去,这种算法结果是错误的
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", arr[i]);
	}

	return 0;
}

Guess you like

Origin blog.csdn.net/2201_75366661/article/details/128902129