C language array, one-dimensional and two-dimensional array, string, array in function parameters, empty input buffer, bubble & select sorting

Introduction: the use and creation of a two-dimensional array string, how to transfer the string and array parameters to the function, string pointer, string input and output, the method of emptying the input buffer, selection sorting and bubble sorting.

catalogue

I One dimensional array

1. Creation and definition of one-dimensional array

2. Use of one-dimensional array

3. Calculation of the number and size of array elements

4. Storage of one-dimensional array in memory

5. Avoid array out of bounds

II Two dimensional array

 1. Definition and initialization of two-dimensional array

2. Use of two-dimensional array

3. Storage of two-dimensional array in memory

III Advanced

1. What is the array name or string name

2. Input and output of string

3. Array parameter transfer in function

(1) Define an array to receive

(2) Create a pointer to receive

4. Constant string (string pointer)

5. Common problems of character input and input buffer

IV Bubble sort & select sort

1. Bubble sorting

 2. Optimization of bubble sorting

3. Select Sorting

V epilogue

I One dimensional array

1. Creation and definition of one-dimensional array

(1). Define and initialize one-dimensional array

	int arr1[10] = { 1,2,3,4 };//The definition array can be sized or not
	int arr2[] = { 1,2,3,4,5 };
	int arr3[5] = { 1,2,3,4,5 };
	char arr4[3] = { 'a','b','c' };
	char arr5[3] = { 'a',93,'c' };//93 is the ASCII code value. Printing with type% c will print the string corresponding to the ASCII value. Similarly, printing a character 'a' with type% d will print the corresponding ASCII code value, just like the code in the next paragraph
	char arr6[] = "abcdefg";

When creating a one-dimensional array, you can not specify the size. If you do not specify the size, you need to initialize the array, that is, the array must have content. At this time, the size of the array (number of elements) is determined according to the initialized content, but we need to pay attention to the differences in the following codes.

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

On the surface, both arr1 and arr2 store 'a', 'B', 'C', but in fact they are allocated in memory like this

Pay special attention to this point in the use and creation of character arrays (strings).

2. Use of one-dimensional array

int main()
{
	int arr[10] = { 0 };//The array is not fully initialized here
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		arr[i] = i;
	}
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr[i]);
	}

	return 0;
}

This shows that the subscript of the array starts from 0!! arr[i] is the specific value.

You can also see I < 10 with two red lines. It is recommended that you write it like this, because the number of I < is the number of elements in the array, which is simple and clear.

The printing of one-dimensional arrays is generally realized by printing one by one with a for loop. Similarly, two-dimensional arrays use two for loops

3. Calculation of the number and size of array elements

The size of the array is generally calculated by sizeof

The number of elements in an array is the size of the array (in bytes) divided by the size of a single element

4. Storage of one-dimensional array in memory

One dimensional arrays are stored continuously in memory, from low address to high address

5. Avoid array out of bounds

When we write I < = 10 here, the description will print a total of 11 numbers, but our array size is only defined as 10. At this time, the array will cross the boundary, so we must be careful when writing the program

II Two dimensional array

 1. Definition and initialization of two-dimensional array

Creation of two-dimensional array

	int arr1[3][4];
	char arr2[3][5];
	double arr3[2][4];

Initialization of two-dimensional array

	int arr1[3][4];
	int arr2[3][4] = { {1,2},{3,4} };
	int arr3[][3] = { {1,2,3},{4,5} };//Only when the two-dimensional array is initialized, the row can be omitted, and the column can not be saved in any case

2. Use of two-dimensional array

Two dimensional arrays are operated by two for loops. Similarly, the array subscripts start from 0~

3. Storage of two-dimensional array in memory

Two dimensional arrays are also stored continuously in memory

III Advanced

1. What is the array name or string name

Obviously, the array name and the address of the array are the address of the first element. The values of these three addresses are the same, but they have different functions.

You can see that str+1 and & STR [0] + 1 are the same, Their address + 1 will only cross one element (4 bytes), and the array name and the address of the first element can be equivalent. However, if you directly take out the address of the array and then + 1, you will directly operate the whole array. The address directly crosses 16 bytes of the whole array, which needs to be paid attention to. Generally, the function parameters pass the array name, because we have to operate inside the function This array must be used element by element.

2. Input and output of string

(1) Note the scanf ('% s', str) here, where str does not need to add &. This is because str is the string name, and the string name is the address of the first element, so str here is already an address, so we don't need to add &.

(2) The printf ('% s', str) here is the same. When printing a string, we need to use the% s type, and% s needs to receive the address. Here, we pass the string name str to% s, that is, the address of the first element of the string and the address of' a '. Printf will start printing from' a 'until it encounters the' \ 0 'terminator.

(3) If we want to print a (single) character in the string, we need to use% c, and the subscript of the string also starts from 0.

3. Array parameter transfer in function

(1) Define an array to receive

//Here we define an array int a [] to receive the passed array
void test(int a[])//Void is a return type. We don't need to return anything here, so we use void
{
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		printf("%d ", a[i]);
	}
}

int main()
{
	int arr[5] = { 1,2,3,4,5 };
	test(arr);
	return 0;
}

In the function test, we create an array int a [] to receive and print the contents of array a.

(2) Create a pointer to receive

void test(int* p)//I defined a pointer * p to receive
{
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		p[i] = 6;
	}
}

int main()
{
	int i = 0;
	int arr[5] = { 1,2,3,4,5 };
	test(arr);//Try changing each value of the array to 6
	for (i = 0; i < 5; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

Why can I use a pointer to receive an array? As mentioned earlier, the array name is the address of the first element, so you can also receive it with a pointer. After learning the pointer, we will know that in the array

    int arr[5] = { 1,2,3,4,5 };
	arr[i]=*(arr+i)

Therefore, when passing parameters in the above test(arr), we pass the array name arr, that is, the address of the first element. We can receive it with the pointer int*p. in the function, we can directly use p as the array name. When we use arr[i], where arr is placed in arr[i], P is placed, that is, p[i], which can be used directly in test.

4. Constant string (string pointer)

We know that the array name or string name represents the address of the first element. Similarly, the address of the first element can be stored in the pointer. Therefore, a pointer str1 is created here to point to the character 'a' of the first element. Therefore, in printf, we know that the corresponding address after% s is required, So it's ok to put the address (pointer) str1 directly, and printf will print back from str1 until it meets' \ 0 '.

5. Common problems of character input and input buffer

int main()
{
	int num;
	char ch;
	scanf("%d", &num);
	scanf("%c", &ch);
	return 0;
}

When we try to run this code

You will find that when we input 20 to num and press enter, you want to input ch. at this time, you will find that the program ends after pressing enter.

Before solving this bug, we need to understand a concept called input buffer. In the process of transmitting our data to parameters, we must first pass through the input buffer, and then pass it to parameters together.

When we enter 20, 20 is passed into the input buffer and press enter. At this time, 20 is successfully assigned from the input buffer to num, but the enter is left in the input buffer, because in the ASCII table, enter is also equivalent to a character, The corresponding key value (ASCII) is 13, so when it's your turn to input ch, scanf directly reads the remaining one from the input buffer, so scanf ("% s", & CH) is skipped. Pay attention to this. Carriage return is also equivalent to one character.

How to solve this bug? After scanf, we can clear the input buffer. Here are several methods.

(1)

int main()
{
	int num;
	char ch;
	scanf("%d", &num);
	setbuf(stdin, NULL);
	scanf("%c", &ch);
	return 0;
}

After a scanf input, add a sentence setbuf(stdin, NULL). Stdin is the standard input stream, that is, keyboard input. This sentence means changing the pointer of the keyboard input stream to a null pointer, which can be understood as setting the input buffer empty. Personally, I think this method is more convenient than.

(2)

int main()
{
	int num;
	char ch;
	scanf("%d", &num);
	fflush(stdin);
	scanf("%c", &ch);
	return 0;
}

After a scanf input, add a sentence fflush(stdin). Stdin is the standard input stream, that is, keyboard input. Fflush clears the standard input stream. This method is also good, but it doesn't work in the vs compiler. Others are OK.

(3)

int main()
{
	int num;
	char ch;
	char c;
	scanf("%d", &num);
	c = getchar();
	scanf("%c", &ch);
	printf("%d\n", num);
	printf("%c\n", ch);
	return 0;
}

Define one more character c to receive the carriage return

 

 

IV Bubble sort & select sort

1. Bubble sorting

Bubble sorting is the pairwise comparison between elements, and the larger one will be put back

#include <stdio.h>
void Bubble_sort(int* arr,int sz)//Here, the pointer * arr is used to receive the passed array name, and sz is the number of array elements
{
	for (int i = 0; i < sz - 1; i++)//sz is the number of elements. As mentioned earlier, if the number of elements is sz, then I < sz. sz-1 here is because there are sz elements and sz-1 needs to be sorted, and - 1 is because there is no need to continue when the first number is left.
	{
		for (int j = 0; j < sz - 1 - i; j++)//Because j+1 will be used for the array subscript below, here J < SZ-1 / / you can imagine that sz-1-0 logarithms need to be compared after 0 times of sorting. After one time of comparison, sz-1-1=9 logarithms need to be compared. After another time of comparison, sz-1-2 pairs need to be compared. Therefore, J < sz-1-i can also be understood as reducing one number to be sorted after one time of sorting, 0 times of sorting reduces the number of 0 to be sorted.
		{
			if (arr[j] > arr[j + 1])//If arr[j] is larger than arr[j+1], put it back
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}

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

10 numbers, just compare 10-1 times.

 2. Optimization of bubble sorting

If the array we need to sort has 10 elements, it needs to be sorted 9 times, but we find that it has been sorted 3 times. Then we don't continue to waste computational power to sort it. We just need to add a flag before each sorting

#include <stdio.h>
void Bubble_sort(int* arr,int sz)//Here, the pointer * arr is used to receive the passed array name, and sz is the number of array elements
{
	for (int i = 0; i < sz - 1; i++)//sz is the number of elements. As mentioned earlier, if the number of elements is sz, then I < sz. sz-1 here is because there are sz elements and sz-1 needs to be sorted, and - 1 is because there is no need to continue when the first number is left.
	{

        int flag = 1;//Define a flag flag flag=1


		for (int j = 0; j < sz - 1 - i; j++)//Because j+1 will be used for the array subscript below, here J < SZ-1 / / you can imagine that sz-1-0 logarithms need to be compared after 0 times of sorting. After one time of comparison, sz-1-1=9 logarithms need to be compared. After another time of comparison, sz-1-2 pairs need to be compared. Therefore, J < sz-1-i can also be understood as reducing one number to be sorted after one time of sorting, 0 times of sorting reduces the number of 0 to be sorted.
		{
			if (arr[j] > arr[j + 1])//If arr[j] is larger than arr[j+1], put it back
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;

                flag = 0;//If it is sorted to, it is proved that it is still disordered, flag=0

			}
		}

		if (flag == 1)//If flag==1, it is proved that it has been ordered
		{
			break;//Jump out of the loop and finish sorting
		}

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

3. Select Sorting

The selection sort is similar to the bubble sort. Assuming that the array arr has 10 elements, the selection sort is to find the subscript of the element with the minimum value (qualified) in the last 9 elements, exchange values with the first element, and then perform such operations in the remaining 9 elements.

Complete code

void SelectSort(int* arr)//Select sort
{
	for (int i = 0; i < 10; i++)
	{
		int min = i;
		for (int j = i + 1; j < 10; j++)//Start looking for the minimum value after the ith element
		{
			if (arr[j] < arr[min])
			{
				min = j;
			}
		}
		if (i != min)//If the subscript min changes, the value is exchanged
		{
			int tmp = arr[i];
			arr[i] = arr[min];
			arr[min] = tmp;
		}
	}
}

int main()
{
	int arr[10] = { 8,3,4,5,7,9,4,6,7,1 };
	SelectSort(arr);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

V epilogue

The summary may not be in place. The following structures, functions and pointers will mention arrays again. The relationship between arrays and pointers and functions is still great~

✨ After reading it, you might as well like it~

✨ Your support is the biggest driving force for bloggers' creation

✨ Thank you again for your patience! If you don't understand, please discuss it in the comment area~

❤️ Thank you for your support!!!!!

Keywords: C Back-end

Added by ChaosDream on Fri, 31 Dec 2021 04:32:49 +0200