Elementary C Language--Arrays

Hello, we meet again. After our unremitting efforts and learning, I believe that the coding ability of my friends must have improved a lot. In this chapter, we will talk about arrays.

  1. Creation and initialization of one-dimensional arrays.
    1.1 Creation of an array
    An array is a collection of elements of the same type.

How arrays are created

type_t   arr_name   [const_n];
//type_t 是指数组的元素类型
//const_n 是一个常量表达式,用来指定数组的大小

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];

Facing the code we saw above, we see that constants must be used in the creation of arrays, that is, our subscript reference operator [] must
be a constant value
insert image description here
insert image description here
, but in some compilers, it is still supported to use variables

: Array creation, before the C99 standard, a constant must be given in [], and variables cannot be used. The concept of variable-length
arrays is supported in the C99 standard.

  • 1.2 Array initialization
    Array initialization refers to giving some reasonable initial values ​​(initialization) to the contents of the array while creating the array.

Look at the code:
int arr1[10] = {1,2,3}; 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";

Let's explain one by one

int arr1[10] = {1,2,3} stores ten integers, among which the first three are 1, 2, and 3, followed by 0
int arr2[] = {1,2,3, 4} store four integers
int arr3[5] = {1, 2, 3, 4, 5} store five integers
char arr4[3] = {'a',98, 'c'} store three characters
char arr5[] = {'a','b','c'} stores three characters
char arr6[] = "abcdef" stores a string, but it is seven characters, and the \0 at the end

When the array is created, if you don't want to specify the definite size of the array, you have to initialize it. The number of elements in the array is determined according to the initialization content.
But for the following code to distinguish, how to allocate memory.

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

Arr1 is 'a' 'b' 'c' ' \0'

  • 1.3 The 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;
}

insert image description here

We can see that the subscript of the array starts from 0

The size of an array can be calculated using the sizeof operator.

int arr[10];
int sz = sizeof(arr)/sizeof(arr[0]);
  • 1.4 Storage of one-dimensional arrays in memory
    Next we discuss the storage of arrays in memory.
    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]);//%p打印的是指针变量的地址
 }
 return 0;
}

insert image description here

Through observation, it is found that the address is in hexadecimal, and the difference between each front and back address is 4 bytes, which happens to be an int. It can also be seen that the array is stored continuously during the storage process.

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];

The first one means row, the second one means column. Take the first one int arr[3][4];to represent an int type with three rows and four columns.
insert image description here
Don’t look at it as if it has three rows and four columns. In fact, it is still a continuous array, such as the first There is still a difference of four bytes between the fourth column of one row and the first column of the second row

  • 2.2 Initialization of two-dimensional array
//数组初始化
int arr[3][4] = {
    
    1,2,3,4};
int arr[3][4] = {
    
    {
    
    1,2},{
    
    4,5}};
int arr[][4] = {
    
    {
    
    2,3},{
    
    4,5}};//二维数组如果有初始化,行可以省略,列不能省略
  • 2.3 The use of two-dimensional array
    The use of two-dimensional array is also through subscript.
    look at the 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;//每一行,每一列开始放数
			//按顺序放从0开始
		}
	}
	for (i = 0; i < 3; i++)
	{
    
    
		int j = 0;
		for (j = 0; j < 4; j++)
		{
    
    
			printf("%d ", arr[i][j]);
		}
	}
	return 0;
}

insert image description here

In the above code, we start from 0 to 11 and store them in the array, and then output them in order

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

insert image description here

We can see that the array is also stored continuously, and each element of the two-dimensional array also has a difference of four bytes. Of course, this is related to int. We can also see that the array can be accessed using subscripts, and the one-dimensional The subscripts of dimension arrays all start from 0

Array out of bounds

Array subscripts are limited in scope.
The subscript of the array starts from 0. If the array has n elements, the subscript of the last element is n-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 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, so when programmers
write code, it is best to check it by themselves

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

Because the array subscript starts from 0, 0-9 is exactly ten numbers, and when the subscript is 10, it is the 11th number, so it is out of bounds

Next we are going to talk about a bubble sort, but before we talk about it, we need to understand one thing is the array name
3 What is the array name? ?
Let's look at the following 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;
}

insert image description here

* is a dereferencing operator, which is equivalent to taking out the content. It can be understood in this way. It is just the opposite of the symbol &. Here, I will explain the conclusion in the operator: the array name is the address of the first element, but there are two examples that are not
. Both are operators, one is sizeof and the other is &

insert image description here
It can be seen that the byte size calculated by sizeof is still the size of the entire array

But you may think that getting the address is also getting the address of the first character, as we can see from the following

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

insert image description here

In this way, we can see that the one skipped without taking the address symbol plus one is an integer, but the skipped one with the (&) symbol is ten integers, so the & symbol is the entire address

4 bubble sort

We want to implement a bubble sort from small to large. First of all, we need to know what bubbling is, and bubbling is to compare adjacent elements. If the first is bigger than the second, swap them both.
Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step is done, the last element will be the largest number.
Repeat the above steps for all elements except the last one.
Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

#include <stdio.h>
void mao_pao(int arr[], int sz)
{
    
    
  
    int i = 0;
    for (i = 0; i < sz - 1; i++)
    {
    
    
        int flag = 1;
        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;
                flag = 0;
            }
        }
        if (flag)//如果j的那个循环一次也没执行,就退出
        {
    
    
            break;
        }
    }

    
}



int main()
{
    
    
    int arr[] = {
    
     10,9,8,7,6,5,4,3,2,1 };
    int sz = sizeof(arr) / sizeof(arr[0]);
   
    int i = 0;
    mao_pao(arr, sz);
    //打印
    for (i = 0; i < sz; i++)
    {
    
    
        printf("%d ", arr[i]);
    }

    return 0;
}

This is a simple bubble sort, not only bubble sort, but also selection sort, which will be discussed later

This is the end of today's sharing. Can you leave a like to support the editor, thank you!

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/131501365