当前位置:网站首页>[C language] Pointer elementary knowledge points
[C language] Pointer elementary knowledge points
2022-07-28 20:04:00 【An ran_】
List of articles
1. What is the pointer
(1) The pointer
The pointer is the number of the smallest unit in memory, that is, the address , Pointer in spoken language is generally pointer variable .
(2) Pointer to the variable
Pointer variables are variables used to store addresses , The values stored in this variable are treated as addresses .
(3) The size of the pointer
32 Bit platform (x86 In the environment ) Next 4 Bytes ,64 Bit platform (x64 In the environment ) Next 8 Bytes .
2. Pointers and pointer types
(1) Pointer definition method
Define the way :type+*
for example : Character :char *p=NULL;
plastic :int* p=NULL;
(2) The type of pointer
The type of pointer : Shaping the pointer 、 Floating point pointer 、 Character pointer 、 Array pointer 、 Function pointers, etc .【 What types of variables , The pointer has a corresponding pointer 】
(3) The meaning of pointer type
① Decide to perform the operation —— The pointer ± Integers , The number of bytes skipped determines the step size
② Determine the operation permission after pointer dereference —— You can change the number of a byte in memory
for example :char* The solution application of can only access one byte , and int* Dereference of can be accessed 4 Bytes ,double* Dereference of can be accessed 8 Bytes
· There are corresponding exercises in the follow-up
3. Wild pointer
(1) What is the wild pointer
A wild pointer is a pointer variable whose value is Illegal memory address , The wild pointer is not a null pointer (NULL).
(2) Wild pointer hazards
Wild pointer hazards : It can lead to Memory out of bounds 、 Segment error Other questions .
another : Legal memory addresses include the addresses of defined variables ,malloc The function requests the address to put the heap memory back, but it is not used free Release .
(3) Common avoidance of wild pointers
① Local variable initialization
If the global variable is not initialized, it will be automatically assigned 0, But local variables don't .
So when we define local pointer variables, we'd better use Local pointer variable initialization NULL, The local variable is initialized to 0.
② Do not return a local in a function / Formal variables and local / Address of formal array .
The address of the formal parameter in the function is after the function call 、 Pointer variables are destroyed immediately before assignment , So the address pointed to at this time is illegal .
③ After releasing the address pointed to by the pointer variable, assign the value of the pointer variable to NULL, Do not use the pointer that has been released
④ Avoid pointer operation errors
Improper operation of the pointer will cause the pointer to be a piece of memory that has been used by other processes , To avoid this situation , Make sure that the character array starts with '\0' ending , Their own use Memory function And the length information specified by the memory related function written , Prevent memory overruns .
⑤ Avoid incorrect cast
A common situation is , Under the multi-level dereference operation ,( for example :(int *)((int)a + 1)) take int Or the reshaped data mistakenly believes that an address is forcibly converted to a pointer type 【 The data stored in the pointer variable is essentially an integer 】, Lead to illegal space .
4. Pointer arithmetic
Not all operations on pointers are legal , In fact, there are very few types of operations that pointers can perform , It is mainly divided into the following two categories and three subspecies .
(1) The arithmetic operation of the pointer
C The pointer operation of is limited to the following two forms : The pointer ± Integers 、 The pointer - The pointer . And the former standard definition is only used to point to a pointer to an element in the array
① The pointer ± Integers
When a pointer and an integer perform arithmetic operations , It will always be adjusted according to the appropriate size . This suitable size is The size of the type pointed to by the pointer .
The result of the calculation is Still pointer .
// The first one is
float x[5]={
1,2,3,4,5};
float* p=&x[0];
p++;
// The second kind
double a[5]={
1,2,3,4,5};
double* pa=&a[0];
pa++;
here p++ Here is the pointer p Add 4 Bytes 【float The type is 4 Bytes 】,pa++ Here is the pointer pa Add 8 Bytes 【double The type is 8 Bytes 】
② The pointer - The pointer
Premise : One pointer is allowed only when both pointers point to elements in the same array - Another pointer 【 Assume that the results are meaningful 】.
The value of subtraction is the distance between two pointers in memory ( In terms of the length of an array element , instead of In bytes !!!)
therefore , The result of the calculation is It is of this type between two pointers Number of elements .
(2) The relational operation of pointers
Premise :<、>、>=、<= The operation requires that both before and after the operation point to the elements of the same array .
Common use scenarios
for(vp = &values[N_VALUES]; vp > &values[0];)
{
*--vp = 0;
}
another : Pointers to array elements can only point to elements inside the array , However, when the array is out of bounds due to incorrect operation , It is not allowed when the pointer points to the memory location before the first element of the array , The compiler will directly report an error —— Illegal access to memory , When the pointer points to the memory location after the last element of the array, it will not report an error , But the result Generally, it will be a random value ; Allows a pointer to an array element to be compared with a pointer to the memory location after the last element of the array , However, it is not allowed to compare with a pointer to the memory location before the first element .
The above results are the result of the joint action of standards and operating system memory access requirements .
5. Pointers and arrays
(1) Array name meaning
Array name meaning : It is essentially the address of the first element of the array , Except for two cases ——sizeof( Array name )【 Calculate the size of the entire array 】 as well as & Array name 【 Take the size of the entire array , The type is Array element type (*)[ Number ]】
(2) You can access the array through a pointer
int main()
{
int arr[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int *p = arr; // The pointer holds the address of the first element of the array
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
for (i = 0; i<sz; i++)
{
printf("%d ", *(p + i));
}
return 0; }
6. The secondary pointer
Pointer variables are essentially variables , If it is a variable, it will have an address , A pointer whose content is the address of a pointer variable is a secondary pointer .
7. Pointer array
The essence is array . analogy : Shape array 、 Character array, etc , The type of array element in front , Next is the essence .
so : A pointer array is an array in which every array element is a pointer .
边栏推荐
- Stories of Party members | Li qingai uses cartoons to drive farmers to increase income and become rich
- editor.md中markdown编辑器的实现
- Implementation of strstr in C language
- Leetcode day3 find duplicate email addresses
- Leetcode Day1 score ranking
- 认识中小型局域网WLAN
- 河北:稳粮扩豆助力粮油生产提质增效
- 【经验之谈】关于维修电子设备的几点建议和经验
- The results of the second quarter online moving people selection of "China Internet · moving 2022" were announced
- Common modules of saltstack
猜你喜欢

Cloud computing notes part.2 - Application Management

Integration and implementation of login click graphic verification code in personal blog system

Stories of Party members | Li qingai uses cartoons to drive farmers to increase income and become rich

河北:稳粮扩豆助力粮油生产提质增效

Cell review: single cell methods in human microbiome research

XOR operation and its usage

Implementation of strstr in C language

There is a 'single quotation mark' problem in the string when Oracle inserts data
![[C language] random number generation and `include < time. H > 'learning](/img/bb/3e47bf2e3b25653d9048884d65cda3.png)
[C language] random number generation and `include < time. H > 'learning

High beam software has obtained Alibaba cloud product ecological integration certification, and is working with Alibaba cloud to build new cooperation
随机推荐
Handan, Hebei: expand grassroots employment space and help college graduates obtain employment
Find the memory occupied by the structure
[C language] simulation implementation of strlen (recursive and non recursive)
Servlet learning notes
Using Lex (Flex) to generate lexical analyzer of PL language
Leetcode day4 the highest paid employee in the Department
Deploy ZABBIX automatically with saltstack
Leetcode Day2 consecutive numbers
基于 MinIO 对象存储保障 Rancher 数据
What is the process of swing event processing?
Information management system and games based on C language
Redis笔记
[C language] initial C language reflection and summary
How does app automated testing achieve H5 testing
云计算笔记part.2——应用管理
Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
爬取IP
克服“看牙恐惧”,我们用技术改变行业
一文读懂如何部署具有外部数据库的高可用 K3s
A chip company fell in round B