Some array knowledge and small details in case you don't know

My ability is limited, it is inevitable that there will be errors or lack of details in the description! I hope readers can give feedback on mistakes and places that are not good enough when reading! Grateful!

Table of contents

Creation and initialization of one-dimensional array

Array creation:

Array initialization:

 Some details:

Count of array elements:

Two-dimensional array

Two-dimensional array creation:

Array out of bounds

Bubble sort and array parameter passing

What is bubble sort?

Array parameters:

What exactly is the array name?

array of pointers


In the C language, the concept of an array itself is not complicated, but there are still some detailed concepts that need to be paid attention to. The following is an overview of the array and some detailed records.

Creation and initialization of one-dimensional array

Array creation:

The creation of a one-dimensional array is the same as the declaration of ordinary variables, and the variable type of the array needs to be declared.

int arr1[10]
char arr2[10]
float arr3[10]

The arr1 after the variable type is the name of the array, and the constant in [] can specify the size of the array. (In some editors, variables can be used to specify the size of the array in [] , such as arr[n])

[] is actually a subscript reference operator

Of course, you can also not specify the size of the array in [], let it adapt to the size, the compiler is quite smart, it will automatically generate a space of the corresponding size to store the elements in it

	int main()
	{
		int arr[] = { 1,2,3,4,5 };
		printf("%d", sizeof(arr));
		return 0;
	}

 

We can see that even if the size of the array is not specified, the compiler still correctly allocates space for the array.

Just like garbage sorting, after the variable type is declared, the element type in the array should be the same as the array type. For example, when we create an array of char type, the stored element should be a string.

char arr[] = "hello hello";

Array initialization:

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

int arr[5]= {1,2,3,4,5};

When the array is not fully initialized, the remaining element slots will be filled with 0

int i = 0;
int arr[5] = {1,2,3};
for (i = 0; i < 5 ; i++)
{
    printf ("%d ",arr[i]);
}

It should be noted that the counting of the array starts from 0. When we want to take out the value of an element in the array, we should always pay attention to the subscript of the array.



 Some details:

The storage of strings in memory is shown in the following figure:

For example char arr[] = "hello";

 At the end of the string, is a \0

When the program stores a string, since it opens up space in the memory, it needs to know where the string ends, and \0 is the sign that the program knows the end of the string.

So there is a question, what happens when we deliberately avoid \0?

With arrays we can try to achieve:

	int main()
	{
		int i = 0;
		char arr[] = { 'h','e','l','l','o'};
	
		printf("%s ", arr);		

		return 0;
	}

 

 Appeared! Holding two kunjin knives, screaming and scalding in his mouth

Obviously, due to our deliberate initialization of the array, the program does not know when to stop when accessing the string, and thus accesses too much and gets garbled characters.


Count of array elements:

Sometimes, we need the number of elements in the array, which we can calculate by the following method instead of counting them one by one, but we need to pay attention to the size of the array when the char type array stores strings.

int main()
{
	int arr[10];
	char arr1[] = "one";

	int sz = sizeof(arr) / sizeof(arr[0]);//数组整体的大小除以其元素大小得到其元素个数
	int sz2 = sizeof(arr1) / sizeof(arr1[0]);

	printf("%d ", sz);
	printf("%d ", sz2);

	return 0;
}

 We can see that only 3 characters are put in arr1 but 4 is output. In fact, the reason is that sizeof also includes \0 when calculating the size of the string array, so 4 is output.

Two-dimensional array

Two-dimensional array creation:

int arr[3][4];
char arr[3][5];
double arr[2][4];

There are certain differences between two-dimensional arrays and one-dimensional arrays, the biggest of which is when initializing:

int arr[3][4] = {1,2,3,4};
int arr[3][4] = {
   
   {1,2},{4,5}};
int arr[][4] = {
   
   {2,3},{4,5}};//行可以省略,列不能省略!

Notice! If the two-dimensional array is initialized, the row can be omitted, but the column cannot be omitted!

Printing and storage of two-dimensional arrays:

 arr[3][4] means that the two-dimensional array has 3 rows, and each row has 4 elements.

When you only need to initialize some elements, you can use {} to separate them

int arr[3][4] = {
   
   {1,2},{4,5}};

 0

 This initialization is wrong


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.

Bubble sort and array parameter passing

In bubble sorting, we need to pass the number of elements of the array, which is not difficult, just use the calculation method of sz above.

Before that, let's introduce bubble sort first.

What is bubble sort?

There is an array out of order. We want to sort it in positive order and print it out, then we can use bubble sort. The principle of bubble sort is as follows:

We can find that bubble sorting will arrange the largest numbers backward one by one like a bubble continuously floating up, and each large cycle can ensure that the largest number is in the last place until the sorting is completed. This is the function of bubble sorting basic logic.

We can use logic to write the following code:

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

Failed! Why isn't our bubble function doing what it's supposed to? Can functions be fished these days?

In fact, it is not. The main problem is actually some rules when passing parameters in arrays.

Array parameters:

After debugging statement by statement, I found the problem:

 The value of sz does not get the number of elements of the entire array, but gets a 1, why?

The reason is that when the array is passing parameters, what is passed is: the address of the first element

So it looks like we are passing an entire array here, but in fact it is just a pointer

(Soul Painter is online)

 

 

 

 Therefore, the bubble function does not know how many elements the entire array has, so it cannot be calculated.

The correct code is as follows, there are two forms, but both should calculate the value of sz in the main function and pass it in first :

The formal parameter is an array:


void bubble(int arr[], int sz)
{
	int i = 0;
	int tmp = 0;
	int n = 0;

	for (i = 0; i < sz - 1; i++)
	{
		for (n = 0; n < sz - i - 1; n++)
		{
			if (arr[n] > arr[n + 1])
			{
				tmp = arr[n];
				arr[n] = arr[n + 1];
				arr[n + 1] = tmp;
			}

		}
	}
}

int main()
{
	int arr[] = { 6,8,7,5,4,3,2,1 };
	int n = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);


	bubble(arr, sz);
	for (n = 0; n < sz; n++)
	{
		printf("%d ", arr[n]);
	}
	return 0;
}

The formal parameters are pointers:

void bubble(int* arr,int sz)
{
	//趟数
	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;
			}
		}
	}
}

 At this point, we may have a small question, what is this array name?

What exactly is the array name?

Let's take a look with the following code:

int arr[10] = {1,2,3,4,5};
printf("%p\n", arr);
printf("%p\n", &arr[0]);
printf("%d\n", *arr);

 Conclusion: The array name is the address of the first element.

but! There are two exceptions!

When we put the array name into sizeof:

int arr[10] = {0};
printf("%d\n", sizeof(arr));

 

 sizeof outputs the size of the entire array, which is an exception, that is, when the array name is put into sizeof, sizeof will treat the array name as the entire array and find its size.

Another exception is: &array name, the address of the array is taken out. &Array name, the array name represents the entire array

 Except for these two cases, all array names represent the address of the first element of the array.

array of pointers

An array of pointers is an array of pointers

Create: int *parr[10] = {&a,&b,&c};

Since it belongs to an overview, I won't go into too much detail, but the following is a detailed description of how to use the pointer array to realize the effect of a two-dimensional array:

I want to use the pointer array to achieve the printing effect of the two-dimensional array

I first create 3 one-dimensional arrays:

int arr1[4] ={1,2,3,4}

int arr2[4] ={1,2,3,4}

int arr3[4] ={1,2,3,4}
然后我创建一个指针数组来存放这3个数组。

int * parr[3]={arr1,arr2,arr3};

int i = 0;

for (i = 0;i < 3;i++)

{

int j = 0;

for (j = 0; j < 4; j ++)

{

我希望直接借由这个行列打印直接打印二维数组,那么我要借用这些计数变量来实现。

printf("%d",parr[i][j])明明不是一个二维数组,怎么就可以成功的打印两行呢?

parr[i]这个指针数组,在访问其中的元素的时候,获取的是其中数组的首地址,相当于parr【1】==arr1,我们将parr[i][j]转换过来一看不就是arr1[j]吗?j每次自增1,依次打印其中的元素,这样就可以成功的实现二维数组的效果了!

}

printf("\n");不要忘记换行!

}

Thanks for reading! Hope to help you a little bit!

Guess you like

Origin blog.csdn.net/m0_53607711/article/details/124782829