当前位置:网站首页>7. Relationship between array, pointer and array

7. Relationship between array, pointer and array

2022-07-06 13:26:00 It's Wang Jiujiu

This paper adopts 《C Primer Plus》、《C Traps and defects 》 And the teaching video of bit technology .

Yes C Language array 、 The relationship between pointer and array is explained in detail ; It also summarizes the problems that beginners encounter when using arrays , I hope it will help you .

Catalog

1. One dimensional array

One dimensional array creation

Initialization of one dimensional array

( One ) traditional method

( Two ) Specify initializer (C99)

The use of one-dimensional arrays

Array boundary

Specify the size of the array

One dimensional array storage in memory

2. Two dimensional array

The creation of two-dimensional array

Initialization of 2D array

The use of two-dimensional arrays

Two dimensional array storage in memory

3. Pointers and arrays

What is the array name ?

Operate on the array by address

Array parameters 、 Pointer parameter


1. One dimensional array

One dimensional array creation

An array is a series of elements with the same data type , Data type when creating ordinary variables , It applies to creating arrays .

General format of one-dimensional array creation : Element type Array name [ Constant expression ];

Example 1:

#include<stdio.h>
int main()
{
    int arr1[10];//10 individual int Array of type elements 
	char arr2[20];//10 individual char Array of type elements 
	double arr3[30];//10 individual double Array of type elements 
	return 0;
}

here arr1、arr2、arr3 All array names ,[] Medium 10、20、30 All constants , Well understood. .

Example 2:

#include<stdio.h>

#define n 10

int main()
{
	int arr1[n];//10 individual int Array of type elements 
	return 0;
}

By using define Define constants , You can also create arrays .

Example 3:

#include<stdio.h>

int main()
{
	int n = 10;
	char a[n];
	return 0;
}

The above method is C99 Variable length arrays supported by the standard (VLA) The concept of , stay C99 Before standard [] Must be given a constant .

It is worth noting that : Not all compilers support variable length arrays (VS The compiler does not support ), And variable length arrays have many disadvantages , Not recommended .

The creation and use of arrays are static , Either way you create an array , Do not change its space size in use . If you want to dynamically change the space to store data , You need to learn the knowledge of Dynamic Planning .

Initialization of one dimensional array

( One ) traditional method

The initialization of an array refers to : While creating an array, give the contents of the array some reasonable initial values ( initialization ).

int arr1[5] = {1,2,3,4,5};// Fully initialized 

int arr2[10] = {1,2,3};// Incomplete initialization 

int arr3[] = {1,2,3,4};// The compiler defines the size of the array according to the input 
  • Fully initialized : Give each element in the array its value .
  • Incomplete initialization : Unassigned elements , The compiler automatically initializes to 0.
  • Omit [] Constant in : The compiler will automatically allocate space according to the input .

You need to distinguish between the following two initialization forms

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

The end of the string defaults to ‘\0’, Initialize as a string without input ‘\0’; If it is entered as a single character , You need to enter it separately at the end ‘\0’, also ‘\0’ Take up a byte of space .

What happens if you don't initialize ?

#include<stdio.h>
int main()
{
	char arr1[10];
	printf("%s\n", arr1);
}

As shown in the above code , Created arr1 Array , It includes 10 individual char Data of type , It was not initialized at the beginning of creation , Print arr1 Array .

This is because the array is not initialized , The array is full of junk information , also arr1 An array is char Type of , The compiler cannot find the terminator ‘\0’, When printing, it will always print , The size limit of the array is exceeded .

( Two ) Specify initializer (C99)

In the traditional way , If you want to initialize the last element in an array , This element and all previous elements must be initialized . And in the C99 In the standard , Support initialization for an element , Other uninitialized elements are initialized to 0.

int arr1[5]={0,0,0,0,1};// Initialize the fifth element to 1
int arr2[5] = {[4]=1};// Array index from 0 Start ,4 Represents the fifth element 

arr1 and arr2 The initialization result of is the same .

Example 1:

int main()
{
	int arr1[10] = {[2]=1,[4]=2,3,4,[2]=10};
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr1[i]);
	}
	return 0;
}

From the above example, we can understand the two characteristics of the specified initializer :

  • If there are more values after the initializer :[4]=2,3,4, Then these values will be assigned to the element after the specified initialization element .arr[4] Is initialized to 2 after , Then arr[5] Is initialized to 3,arr[6] Is initialized to 4.
  • If the specified element is initialized again , Then the last initialization will replace the previous initialization . for example [2]=1, In the beginning 1 The value is assigned to arr1[2], however arr1[2] Later [2]=10 Initialize to 10.

What happens if you don't specify the size of the array ?

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

The compiler will allocate space reasonably according to the specified initialization contents , The last element initialized is arr[6], So the compiler assigns 7 Space of elements .

The use of one-dimensional arrays

After declaring the array , With the help of the subscript of the array, it can be assigned .

#define num 5
int main()
{
	int arr1[num] = {0};
	int i = 0;
	for (i = 0; i < num; i++)
	{
		arr1[i] = i;
	}
	return 0;
}

C It is not allowed to assign an array as a value to another array , Besides initialization , Assignment in curly brackets is not allowed , The following is an example of an error :

#define num 5
int main()
{
	int arr1[num] = { 1,2,3,4,5 };
	int arr2[num] = { 0 };

	arr2 = arr1;// Don't allow 
	arr1[num] = arr2[num];// Array subscript out of bounds 
	arr2[num] = { 1,2,3,4,5 };// Invalid 
	
	return 0;
}
  • arr1[num] = arr2[num] Understood as a : take arr2 Subscript is num The elements of , Assign its value to arr1 Subscript is num The elements of , however arr1 and arr2 The maximum subscript of the element in is num-1, Cross border visit .
  • If you change it to arr1[num-1] = arr2[num-1], Only the subscript is [num-1] Element assignment , It is not an array assignment operation .

Array boundary

When using arrays , You need to prevent the array subscript from going beyond the boundary , You must ensure that the array subscript is a valid value .

for example :

int main()
{
	int arr1[5] = { 1,2,3,4,5 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr1[i]);
	}
	putchar('\n');
	return 0;
}

arr1 Valid subscripts in the array are 0~4, When the visit crosses the boundary , What you print is meaningless numbers . But the compiler does not report an error , It works . This is because C The principle that languages trust programmers , Do not check boundaries . in order to C Languages can run faster , It is not necessary for the compiler to catch all subscript errors . In order to prevent access out of bounds , When declaring an array, use a symbolic constant to represent the size of the array .

Specify the size of the array

When creating an array earlier , Three examples are given to specify the size of the array , Here are various methods of specifying the size of an array in more detail :

#define size 5
int main()
{
	int a1[size];// Sure , Integer symbolic constant 
	int a2[5];// Sure , Literal constants of integers 
	int a3[5 * 2 - 1];// Sure , Integer constant expression 
	int a4[0];// Can not be , Array size must be greater than 0
	int a5[-1];// Can not be , Array size must be greater than 0
	int a6[2.5];// Can not be , Array size must be an integer 
	int a7[(int)2.5];// Sure , Cast type to integer 
	int a8[sizeof(int)]; Sure ,sizeof Expressions are treated as integral constants 
	int n = 5;
	int a9[n]; // Variable length array VLA,C99 Not allowed before 
	return 0;
}

It is worth noting that ,const Modified constant variable , Although it has constant properties , But the essence is a variable ,C99 It is not allowed to use const Decorated constants specify the size of the array .

 

One dimensional array storage in memory

Create an integer array , Print its address ( With X86 Environment, for example )

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

give the result as follows :

Through observation, we can know : Array elements are stored continuously , As the subscript increases, it points from low address to high address , In this case arr Is an integer array , So the interval between each element 4 Bytes .

2. Two dimensional array

The creation of two-dimensional array

General format of one-dimensional array creation : Element type Array name [ Constant expression 1][ Constant expression 2]; expression 1 Is the row of the array , expression 2 Is the column of the array .

int arr1[3][3];
char arr1[3][3];
double arr1[3][3];

Initialization of 2D array

int arr[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
int arr[3][3] = { 1,2,3,4,5,6,7,8,9 };// As long as the corresponding value is correct , You can also omit the inner parentheses 
int arr[][3] = { 1,2,3,4,5,6,7,8,9 };// On initialization , Lines can be omitted , Columns cannot be omitted 

example 1:

What is the result of initializing the array with the following code ?

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

result :

  Like a one-dimensional array , Uninitialized elements default to 0.

example 2:

What is the result of initializing the array with the following code ?

int arr5[][3] = { {1,2,3},{(4,5),5},{7}};

  result :

(4,5) Is a comma expression , Take the latter when assigning values 5.

The use of two-dimensional arrays

Like a one-dimensional array , The use of two-dimensional arrays is also used for Loop traversal , The difference is that a two-dimensional array requires two for Loop nesting .

Print a two-dimensional array :

int arr[][3] = {1,2,3,4,5,6,7,8,9};
	int i = 0, j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			printf("%d ", arr[i][j]);
		}
		printf("\n");
	}

Two dimensional array storage in memory

Print the address of each bit in the two-dimensional 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;
}

result :

Through observation, we found that , The storage of two-dimensional arrays is also continuous , First store the elements in the first row , Then store the second line , And so on .

3. Pointers and arrays

Pointers provide a way to use addresses in symbolic form , Using pointers can store data more efficiently , The array uses pointers in disguise ?

What is the array name ?

For a one-dimensional array , The array name is the address of the first element .

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

Print arr Address and arr First element arr[0] The address of , It is found that the two are the same . Through to arr Dereference of address *, You can find the first element of the array 1.

For a two-dimensional array , The array name is the address of the first element .

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

  result :

The address of the first line element is equal to the address of the first element in the first line , Print arr And the address of the first element in the first line , It is found that they are the same .(*arr)[0] Expressed as : Through to arr Dereference and find the first line , Then find the subscript in the first line 0 The elements of , namely 1.

Operate on the array by address

Print every bit of a one-dimensional array

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

Print every bit of the two-dimensional array

#include <stdio.h>
#define n 3
int main()
{
	int arr[][n] = { 1,2,3,4,5,6,7,8,9};
	int i = 0, j = 0;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			printf("%d ", *( * (arr + i)+j));
		}
		putchar('\n');
	}
	return 0;
}

Array parameters 、 Pointer parameter

Design a function , The return value is the sum of all integers in the array .

Several forms of one-dimensional array parameters :

Array form :

#include <stdio.h>

int text1(int arr[],int sz)//int arr[3] Yes ,arr[] Are there any numbers in the same 
{
	int i = 0;
	int sum = 0;
	for (i = 0; i < sz; i++)
	{
		sum += arr[i];
	}
	return sum;
}


int main()
{
	int arr[3] = {1,2,3};
	int sz = sizeof(arr) / sizeof(arr[0]);
	return 0;
}

Because the array name is the address of the first element , The incoming to text Function , It looks like arr Or arrays , In fact, it's just the address of the first element , You also need to change the size of the array sz Also the incoming text Function .

Pointer form :

int text(int* arr, int sz)
{
	int i = 0;
	int sum = 0;
	for (i = 0; i < sz; i++)
	{
		sum += *(arr+i);
	}
	return sum;
}

Several forms of two-dimensional array parameters :

Array form :

#include <stdio.h>
#define ROW 3
#define COL 3

int text(int arr[][ROW], int row,int col)//int arr[][ROW] Reception time , You can omit lines , You can't omit Columns 
{
	int i = 0, j = 0;
	int sum = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			sum += arr[i][j];
		}
	}
	return sum;
}

int main()
{
	int arr[ROW][COL] = {1,2,3,4,5,6,7,8,9};
	printf("%d\n", text(arr, ROW,COL));
	return 0;
}

Pointer form :

#include <stdio.h>
#define ROW 3
#define COL 3

int text(int (*arr)[ROW], int row, int col)
{
	int i = 0, j = 0;
	int sum = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			sum += *(*(arr+i)+j);
		}
	}
	return sum;
}

int main()
{
	int arr[ROW][COL] = { 1,2,3,4,5,6,7,8,9 };
	printf("%d\n", text(arr, ROW, COL));
	return 0;
}

The essence of array form and pointer form is the use of address , There is no difference between the two in essence .

Mine clearance and Sanzi The core idea of is the use of two-dimensional arrays .

原网站

版权声明
本文为[It's Wang Jiujiu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916176297.html