"C Language Elementary" Chapter 5 - Array

definition

数组是一组相同类型元素的集合, but when we need to create multiple variables of the same type, we only need to create an array of one type, which is equivalent to creating many variables of the same type at the same time.


one-dimensional array

How arrays are created

Let's start with the definition and look at the creation of the array:

type_t arr_name[const_n];
  • type_trefers to the type of the element;
  • arr_nameis the array name;
  • const_nis a constant expression used to specify the size of the array;

It can be simplified as:
element type array name [number of elements]
eg:

int arr[10] 

Means: Create an array named arr, which stores 10 elements, each element type is int type

variable length array

When creating an array, we may think of using the following method to create an array

int n=10;
int arr[n];

Of course, this method is not feasible
. The reason: before the c99 standard, the size of the array can only be . 常量表达式In the c99 standard, the concept of variable length array is introduced 变量, so that the size of the array 不能初始化can be . The compiler (IDE) does not support variable-length arrays in c99, but the gcc compiler can.

array initialization

When a one-dimensional array is created, if no definite array size value is given, the array must be initialized, and the size of the array is determined according to the initial content. Therefore, the initialization of the array refers to giving some reasonable initial values ​​to the contents of the array while creating the array.

usage example

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

Use of one-dimensional arrays

  • We generally use the operator: [ ] (subscript reference operator) to access elements at a certain position in the array;
  • The subscripts of array elements start from 0

usage example

Enter ten numbers from the keyboard and print them on the screen

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

We generally use the keyword sizeof to find the length of an array

  • sizeof(arr)表示整个数组的大小
  • sizeof(arr[0])表示计算数组中首元素的大小,即每个元素的大小
  • 数组元素个数=数组总大小/数组每个元素大小

One-dimensional array storage

How are arrays stored in memory? Let's look at a piece of code first:

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

注意:%p是打印地址的格式输出符号
This code prints the address of each element of the array, and the result is as follows:
insert image description here
According to the result, as the subscript of the array increases, the address of the element increases regularly, and the address difference of adjacent elements is 4, which is exactly one The size of the int type, so we know that the array is stored continuously in memory.


Two-dimensional array

Creation of two-dimensional array

Two-dimensional arrays are created very similarly to one-dimensional arrays

type_t arr_name[row][col];
  • type_trefers to the type of the element;
  • arr_nameis the array name;
  • rowis a constant expression that specifies the number of rows in the array;
  • colis a constant expression that specifies the number of columns in the array;

usage example

int arr[3][4];//创建一个3行4列的整形二维数组
char arr1[3][5];//创建一个3行5列的字符二维数组
double arr3[2][4];//创建一个2行4列的浮点型二维数组

Initialization of two-dimensional array

//数组初始化
int arr[3][4] = {
    
    1,2,3,4};//将第一行赋值1,2,3,4,其余行的数默认为0;
//表示第1行{1,2},第2行{4,5}
//最终效果:
//1 2 0 0
//4 5 0 0
//0 0 0 0
int arr[3][4] = {
    
    {
    
    1,2},{
    
    4,5}};
int arr[][4] = {
    
    {
    
    2,3},{
    
    4,5}};//二维数组如果有初始化,行可以省略,列不能省略
  • 数组的不完全初始化,其他内容默认为0
  • 二维数组初始化时,行可以省略,列不能省略

Use of two-dimensional arrays

Two-dimensional arrays are accessed in the form of array name[row][column]

usage example

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

Two-dimensional array storage

As before, take a look by printing the address of each element:

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

insert image description here
Through observation, it is found that:

  • The addresses of adjacent elements in each row of a two-dimensional array differ by 4, which is exactly intthe size of a type
  • The address of the last element of each row is also different 4
    from the address of the first element of the next row. It can be seen that, like a one-dimensional array, a two-dimensional array is also stored continuously in memory.

Array out-of-bounds access

When we create an array, we all know that the subscript is limited by the range.

  • 数组的下标规定是从0开始,如果数组由n个数组组成,那么元素的下标范围就是0到-1
  • 所以当数组的下标小于0或者大于n-1,就是数组越界访问,超出了数组合法空间的访问

Note: The C language itself does not perform an out-of-bounds check for array subscripts, and the compiler does not necessarily report an error, but the fact that the compiler does not report an error does not mean that the program is correct.

Example of array out of bounds

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

For array out-of-bounds access, we cannot know whether the space accessed out-of-bounds is dangerous, nor can we predict other consequences.

array as function parameter

  • 通常情况下,数组名是首元素地址
  • sizeof(数组名):计算的是整个数组的大小,sizeof内部单独放一个数组名,数组名表示整个数组
  • &数组名:取出的是数组的地址,&数组名,数组名表示整个数组
#include<stdio.h>
int main()
{
    
    
	int arr[5] = {
    
     0,1,2,3,4 };
	printf("  arr=%p\n", arr);
	printf("arr+1=%p\n", arr + 1);
	printf("\n");
	printf("  &arr[0]=%p\n", &arr[0]);
	printf("&arr[0]+1=%p\n", &arr[0] + 1);
	printf("\n");
	printf("  &arr=%p\n", &arr);
	printf("&arr+1=%p\n", &arr + 1);
	return 0;
}

insert image description here

Bubble Sort

Applicable conditions: Integer arrays are sorted in ascending order

usage example

error example

#include <stdio.h>
void bubble_sort(int arr[])
{
    
    
	int sz = sizeof(arr) / sizeof(arr[0]);
	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[] = {
    
     5,3,7,6,1,8,9,2,4,0 };
	bubble_sort(arr);
    int i = 0;
	for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

This code star believes that many small partners can’t see any problems, but the running result is wrong. The reason is that sizeof(arr) calculates the size of the array, and when arr is passed into the function, arr will no longer It is an array, but an address, that is, the first address of the array, so when we use sizeof to calculate the size of an address, there will be a big error.

correct example

#include<stdio.h>
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[] = {
    
     5,3,7,6,1,8,9,2,4,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	bubble_sort(arr, sz);
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/hsjsiwkwm/article/details/131979210