当前位置:网站首页>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
One dimensional array creation
Initialization of one dimensional array
( Two ) Specify initializer (C99)
The use of one-dimensional arrays
One dimensional array storage in memory
The creation of two-dimensional array
The use of two-dimensional arrays
Two dimensional array storage in memory
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 .
边栏推荐
- Decomposition relation model of the 2022 database of tyut Taiyuan University of Technology
- Floating point comparison, CMP, tabulation ideas
- 2-year experience summary, tell you how to do a good job in project management
- 阿里云微服务(二) 分布式服务配置中心以及Nacos的使用场景及实现介绍
- 面试必备:聊聊分布式锁的多种实现!
- Pit avoidance Guide: Thirteen characteristics of garbage NFT project
- 4.30动态内存分配笔记
- Abstract classes and interfaces
- 1.初识C语言(1)
- Cloud native trend in 2022
猜你喜欢
8.C语言——位操作符与位移操作符
Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
Database operation of tyut Taiyuan University of technology 2022 database
10 minutes pour maîtriser complètement la rupture du cache, la pénétration du cache, l'avalanche du cache
Questions and answers of "signal and system" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
Relational algebra of tyut Taiyuan University of technology 2022 database
View UI plus released version 1.3.0, adding space and $imagepreview components
西安电子科技大学22学年上学期《信号与系统》试题及答案
Conceptual model design of the 2022 database of tyut Taiyuan University of Technology
View UI Plus 发布 1.2.0 版本,新增 Image、Skeleton、Typography组件
随机推荐
Pit avoidance Guide: Thirteen characteristics of garbage NFT project
继承和多态(上)
魏牌:产品叫好声一片,但为何销量还是受挫
TYUT太原理工大学2022软工导论简答题
Common method signatures and meanings of Iterable, collection and list
TYUT太原理工大学2022数据库之关系代数小题
阿里云微服务(三)Sentinel开源流控熔断降级组件
arduino+DS18B20温度传感器(蜂鸣器报警)+LCD1602显示(IIC驱动)
string
Tyut Taiyuan University of technology 2022 "Mao Gai" must be recited
E-R graph to relational model of the 2022 database of tyut Taiyuan University of Technology
系统设计学习(二)Design a key-value cache to save the results of the most recent web server queries
最新坦克大战2022-全程开发笔记-1
TYUT太原理工大学2022数据库考试题型大纲
西安电子科技大学22学年上学期《射频电路基础》试题及答案
8.C语言——位操作符与位移操作符
View UI Plus 发布 1.1.0 版本,支持 SSR、支持 Nuxt、增加 TS 声明文件
六种集合的遍历方式总结(List Set Map Queue Deque Stack)
View UI plus released version 1.3.0, adding space and $imagepreview components
凡人修仙学指针-2