Elementary C language - array

Posted by spetsacdc on Sat, 26 Feb 2022 13:13:52 +0100

catalogue

Creation of one-dimensional array

Initialization of one-dimensional array

Use of one-dimensional array

Storage of one-dimensional array in memory

Creation of two-dimensional array

Initialization of two-dimensional array

Use of two-dimensional arrays

Storage of two-dimensional array in memory

Array out of bounds

Array as function parameter

Creation of one-dimensional array

Definition of array: an array is a collection of elements of the same type
Creation method: element type array name [array size (constant expression)]
If int arr [variable] is to be used, C99 syntax must support variable length arrays.

Initialization of one-dimensional array

Initialization: give the contents of the array some initial values while creating the array
If the memory space of the array is full, it is called full initialization. For example, int arr[4]={1,2,3,4};
If it is not completely filled, it will automatically fill in 0 (character array will fill in \ 0), which is called incomplete initialization. For example, int arr[4]={1,2}
There is also a special array: int arr[]={1,2,3,4}. At this time, [] automatically determines the number of elements according to the initialization content

-Initialization of character array:

  • char ch1[5]={'s','b'};//s b \0 \0 \0
  • char ch2[]={'s','b'};//s b

  • char ch3[5]="sb";//s b \0 \0 \0
  • char ch4[]="sb";//s b \0

  • char ch5[]="sb";//s b \0
  • char ch6[]={'s','b'};//s b

Use of one-dimensional array

[] is the subscript reference operator, which is the operator of array access.
Arrays are accessed using subscripts that start at 0
The number of elements of the array can be calculated by sizeof(). You only need to calculate the memory occupied by the array / the memory occupied by an element in the array, and the result is the number of elements

Storage of one-dimensional array in memory

#include <stdio.h>
int main()
{
 int arr[10] = {0};
 int i = 0;
    int sz = sizeof(arr)/sizeof(arr[0]);//Find the number of array elements
    
 for(i=0; i<sz; ++i)
 {
 printf("&arr[%d] = %p\n", i, &arr[i]);//%p - is printed in address format - hexadecimal printing
 }
 return 0;
}

Program running results

It is not difficult to find that each address differs by 4 because the memory size of each integer element is 4 bytes
Conclusion: 1 One dimensional arrays are stored continuously in memory As the array subscript grows, the address changes from low to high
So the pointer we use can operate as follows:

#include <stdio.h>
int main()
{
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10};
    int* p = arr;//The array name is the address of the first element of the array
    int i = 0;
    for(i=0;i<10;i++)
    {
        printf("%d  ",*p);//*p is a dereference operation
        p++;//*P is modified by int, so adding 1 to p is equal to adding 4 bytes, so p + + can jump to the next bit
    }
    return 0;
}

Creation of two-dimensional array

int arr[3] [4];// Three rows and four columns
char arr[3] [5];// Three rows and five columns

Initialization of two-dimensional array

int arr[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};// Define three rows and four columns, fill the elements from the first row, and wrap when the row is filled
int arr[3][4]={1,2,3,4,5,6,7} / / incomplete initialization - followed by 0
int arr[3][4]={ {1,2}, {3,4}, {5,6} };// It is also incomplete initialization, but the form of complement 0 has changed. First line: {1,2,0,0}, second line: {3,4,0,0}, third line {5,6,0,0}
Rows of two-dimensional array can be omitted, but columns cannot be omitted! For example, int arr [] [4] = {1,2}, {3,4}, {5,6};

Use of two-dimensional arrays

Two dimensional arrays are also accessed by subscript. Rows and columns start from 0

#include <stdio.h>
int main()
{
    int arr[][4] = { {1,2},{3,4},{5,6} };//Define 3 rows and 4 columns
    int i = 0;
    int j = 0;
    for (i = 0; i < 3; i++)
    {
        int j = 0;
        for (j = 0; j < 4; j++)
        {
            printf("%d ", arr[i][j]);//Define a cycle to print each bit
        }
        printf("\n");//Wrap every line you print.
    }
    return 0;
}

Storage of two-dimensional array in memory

#include <stdio.h>
int main()
{
	int arr[][4] = { {1,2},{3,4},{5,6} };//Define 3 rows and 4 columns
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		int j = 0;
		for (j = 0; j < 4; j++)
		{
			printf("arr[%d][%d]=%p ", i,j,&arr[i][j]);//Define a cycle to print the address of each bit
		}
		printf("\n");
	}
	return 0;
}

Program running results

Observing the address difference, it is found that there is a difference of four bytes from left to right, and each line break is also a difference of four bytes.
It is concluded that:
Two dimensional arrays are also stored continuously in memory! The same line is continuous internally and across lines

Array out of bounds

The lower specification 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, the array is accessed beyond the bounds and beyond the access of the legal space of the array.
C language itself does not do the cross-border check of array subscripts, and the compiler does not necessarily report errors, but if the compiler does not report errors, it does not mean that the program is correct. Therefore, when programmers write code, they'd better do the cross-border check themselves.
Rows and columns of two-dimensional arrays may also be out of bounds.

Array as function parameter

When we write code, we often pass arrays as parameters to functions
For example: bubble sorting is used to arrange all the numbers in the array from small to large.
So here we have to introduce the bubble sorting algorithm.
Bubble sorting: two adjacent elements are compared and may need to be exchanged

Idea: if the value stored in our array is 9 8 7 6 5 4 3 2 10 elements in total, we need to compare 9 and 8 first. If 9 > 8, we will exchange positions, and then compare 9 and 7. If 9 > 7, we will exchange positions... Until 9 and all the numbers are compared, this bubble sorting is over. Then we think, 10 numbers, we have to carry out 9 bubble sorting, because the last number must be the smallest, so there is no need to sort again. Therefore, the number of bubble sorting times is equal to the number of elements - 1. Then we analyze the interior of bubble sorting. The first bubble sorting has 10 numbers, so we need to compare the first element with the other 9 elements and exchange them; In the second bubble sorting, compare the first element with the other 8 elements... That is, the judgment times of bubble sorting should be less than the number of elements - 1, and then subtract the number of times, because the number of times is the number of elements that do not need to be judged. The idea is roughly the same, so we should also consider the efficiency. If the value of array memory is 1 2 3 4 5 6 7 8 9, it is obvious that it has been sorted, but if our program is just like this, it will continue to judge, but it will not exchange, but this greatly reduces the efficiency of our program. So we grasp the key point: the sorted array will not be exchanged again, that is, it will not enter the judgment part of the exchange, so we can write a tag variable with a value of 1. If the exchange occurs, the value of the tag variable will change to 0, and then if the program runs to the exchange part and there is no exchange, break;
So the source code is as follows:

#define _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>
void bubble_sort(int arr[], int sz)//The essence of formal parameter arr is pointer
{
    int i, j;
        for (i = 0; i < sz - 1; i++)
        {
            int j = 0;
            int flag = 1;//Tag variable
            for (j = 0; j < sz - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])//Exchange part
                {
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                    flag = 0;
                }
            }
            if (flag ==1)//Marking part
            {
                break;
            }
        }
}
int main()
{
    int arr[] = { 3,1,7,5,8,9,0,2,4,6 };
    int sz = sizeof(arr) / sizeof(arr[0]);/*The address of the first element is passed through the array parameter, so sz must be carried out outside the function, if it is in the bubble_ In the sort function, the result is 1*/
    bubble_sort(arr, sz);
    int i;
    for (i = 0; i < sz; i++)
    {
        printf("%d ", arr[i]);
    }
    return 0;
}

– verify that the array name is the address of the first element:

#include <stdio.h>
int main()
{
	int arr[] = { 0 };
	printf("%p\n",&arr[0]);
	printf("%p", arr);
	return 0;
}

Program running results

However, the array name is not always the address of the first element, with two exceptions:
1. Sizeof (array name) – the array name represents the entire array – calculates the size of the entire array in bytes
2. & array name – the array name represents the whole array – the address of the whole array is taken out
Let's verify & whether the address of the whole array is retrieved:

#include <stdio.h>
int main()
{
	int arr[] = { 0 };
	printf("%p\n",&arr[0]);
	printf("%p\n", arr);
	printf("%p\n", &arr);
	return 0;
}

Program running results

As like as two peas, the three questions are exactly the same. As we just said, & array name - takes out the address of the whole array, which is not wrong, because the address of the array starts from the address of the first element, and & arr [0] and arr are the first address of the taken element. Pay attention to distinguish this subtle difference. We verify as follows:

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

 

Here we can clearly see that & arr + 1 is the address + 1 of the whole array, and arr just jumps from the address of the first element to the address of the second element

be careful:

When an array is passed as a function parameter, the formal parameter can be written in two forms (essentially a pointer, but can be written as an array):
1. Array form
2. Pointer form

This chapter is over here. If you practice the array operation, you can see the Sanzi chess and mine sweeping projects. I hope you can gain something.

Topics: Java C C++ Back-end