当前位置:网站首页>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 .
边栏推荐
- TYUT太原理工大学2022“mao gai”必背
- C语言实现扫雷游戏(完整版)
- Alibaba cloud microservices (III) sentinel open source flow control fuse degradation component
- View UI plus released version 1.2.0 and added image, skeleton and typography components
- 六种集合的遍历方式总结(List Set Map Queue Deque Stack)
- 初识C语言(上)
- Branch and loop statements
- 4.30 dynamic memory allocation notes
- Wei Pai: the product is applauded, but why is the sales volume still frustrated
- Introduction and use of redis
猜你喜欢
Application architecture of large live broadcast platform
Alibaba cloud side: underlying details in concurrent scenarios - pseudo sharing
9.指针(上)
Quickly generate illustrations
Design a key value cache to save the results of the most recent Web server queries
1.C语言矩阵加减法
阿里云微服务(三)Sentinel开源流控熔断降级组件
2-year experience summary, tell you how to do a good job in project management
Tyut Taiyuan University of technology 2022 introduction to software engineering summary
西安电子科技大学22学年上学期《基础实验》试题及答案
随机推荐
arduino+DS18B20温度传感器(蜂鸣器报警)+LCD1602显示(IIC驱动)
Record: I accidentally wrote a recursion next time
Interview Essentials: talk about the various implementations of distributed locks!
Application architecture of large live broadcast platform
学编程的八大电脑操作,总有一款你不会
Answer to "software testing" exercise: Chapter 1
Arduino+ds18b20 temperature sensor (buzzer alarm) +lcd1602 display (IIC drive)
Small exercise of library management system
E-R graph to relational model of the 2022 database of tyut Taiyuan University of Technology
【话题终结者】
CorelDRAW plug-in -- GMS plug-in development -- Introduction to VBA -- GMS plug-in installation -- Security -- macro Manager -- CDR plug-in (I)
Alibaba cloud microservices (III) sentinel open source flow control fuse degradation component
2.初识C语言(2)
阿里云微服务(二) 分布式服务配置中心以及Nacos的使用场景及实现介绍
string
西安电子科技大学22学年上学期《信号与系统》试题及答案
A brief introduction to the database of tyut Taiyuan University of technology in previous years
最新坦克大战2022-全程开发笔记-3
Iterable、Collection、List 的常见方法签名以及含义
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