当前位置:网站首页>013 basics of C language: C pointer
013 basics of C language: C pointer
2022-06-27 04:24:00 【Prison plan progress 50%】
List of articles
- One : introduce
- Two : What is a pointer
- 3、 ... and : How to use the pointer
- Four :C Medium NULL The pointer
- 5、 ... and :C Pointer description
- 6、 ... and : The arithmetic operation of the pointer
- 7、 ... and : Pointer array
- 8、 ... and : The pointer to the pointer
- Nine : Passing pointers to functions
- Ten : Return pointer from function
One : introduce
Study C The pointer of language is simple and interesting . Through the pointer , It can be simplified C Execution of programming tasks , There are other tasks , Such as dynamic memory allocation , Can't execute without a pointer .
Each variable has a memory location , Each memory location defines a hyphen that can be used (&) Address accessed by operator , It represents an address in memory .
example :
#include <stdio.h>
int main(){
int var1;
char var2[10];
printf("var1 address is : %x \n", &var1);
printf("var2 address is : %x \n", &var2);
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim zhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc zhizhen.c -o zhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./zhizhen
var1 address is : 387d966c
var2 address is : 387d9662
Through the above example , We learned what a memory address is and how to access it . Now let's see what a pointer is .
Two : What is a pointer
The pointer is a variable , Its value is the address of another variable , The direct address of the memory location . Just like other variables or constants , Before using pointers to store other variable addresses , Declare it .
The general form of pointer variable declaration is :type *var-name;
ad locum type Is the basic type of pointer , Must be an effective C data type ,var-name Is the name of the pointer variable , The asterisk is used to specify that a variable is a pointer . for example :
int *ip; /* Pointer to an integer */
double *dp; /* One double Pointer to type */
float *fp; /* A floating point pointer */
char *ch /* A character pointer */
The actual data type of the value of all pointers , Whether it's an integer 、 floating-point 、 Character , Or other data types , It's all the same , Is a long hexadecimal number representing the memory address .
The only difference between pointers of different data types is , The data type of the variable or constant that the pointer points to is different .
3、 ... and : How to use the pointer
The following operations are frequently performed when using pointers : Define a pointer variable 、 Assign variable address to pointer 、 Access the value of the address available in the pointer variable . These are through the use of unary operators * To return the value of the variable at the address specified by the operand .
example :
#include <stdio.h>
int main(){
int var = 20; // Declaration of actual variables
int *ip; // Declaration of pointer variables
ip = &var; // Store... In pointer variables var The address of
printf("value of &var: %x \n", &var);
printf("value of ip: %x \n", ip); // Address stored in pointer variable
printf("value of *ip: %x \n", *ip); // Use pointers to access values
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim use_zhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc use_zhizhen.c -o use_zhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./use_zhizhen
value of &var: ae0c8004
value of ip: ae0c8004
value of *ip: 14
Get data through pointer variables
Pointer variables store the address of the data , The data on the address can be obtained through the pointer variable , The format is :*pointer;
there * This is called the pointer operator , Used to get data at an address , Please see the following example :
#include <stdio.h>
int main(){
int a = 15;
int *p = &a;
printf("%d, %d\n", a, *p); // Both methods can output a Value
return 0;
}
Running results :
15, 15
hypothesis a The address is 0X1000,p Point to a after ,p The value itself will become 0X1000,*p To get an address 0X1000 The data on the , That's the variable a Value . From the running results ,*p and a It is equivalent. .CPU Reading and writing data must know the address of the data in memory , Ordinary variables and pointer variables are mnemonics for addresses , Though through *p and a The data we get is the same , But they work a little differently :a It takes only one operation to get the data , and *p It takes two operations , One more layer “ indirect ”.
Hypothetical variables a、p The addresses of are 0X1000、0XF0A0, Their pointing relationship is shown in the figure below :
p a
--------- ---------
| 0X1000 | ----> | 15 |
|--------| |--------|
0XF0A0 0X1000
adopt *p get data adopt a get data
After the program is compiled and linked ,a、p Replaced with the corresponding address . Use *p Words , You have to go through the address first 0XF0A0 Get variables p It's worth it , This value is a variable a The address of , Then we get the variable by this value a The data of , There are two operations before and after ; While using a Words , You can use the address 0X1000 Get its data directly , Just one step operation . in other words , Using a pointer is an indirect way to get data , Using variable names is to get data directly , The former costs more than the latter .
Pointers can get data in memory , You can also modify the data in memory , for example :
#include <stdio.h>
int main(){
int a = 15, b = 99, c = 222;
int *p = &a; // Defining pointer variables
*p = b; // Modify the data in memory through pointer variables
c = *p; // Get data in memory through pointer variables
printf("%d, %d, %d, %d\n", a, b, c, *p);
return 0;
}
Four :C Medium NULL The pointer
When variables are declared , If there is no exact address to assign , Assign a... To the pointer variable NULL Value is a good programming habit . To assign as NULL A pointer to a value is called a null pointer .NULL Pointer is a constant defined in the standard library with a value of zero .
example :
#include <stdio.h>
int main(){
int *ptr = NULL;
printf("ptr The value of is %x \n", ptr);
return 0;
}
result :
ptr The value of is 0
On most operating systems , The program does not allow access to address 0 Of memory , Because the memory is reserved by the operating system . However , Memory address 0 Of particular importance , It indicates that the pointer does not point to an accessible memory location .
5、 ... and :C Pointer description
| Concept | describe |
|---|---|
| The arithmetic operation of the pointer | You can do four arithmetic operations on the pointer :++、–、+、- |
| Pointer array | You can define an array to store pointers . |
| The pointer to the pointer | C Allow pointer to pointer . |
| Passing pointers to functions | Passing parameters by reference or address , Make the passed parameters change in the calling function . |
| Return pointer from function | C Allows functions to return pointers to local variables 、 Static variables and dynamic memory allocation . |
6、 ... and : The arithmetic operation of the pointer
6.1: summary :
C A pointer is an address represented by a number , therefore , You can perform arithmetic operations on pointers , You can do four arithmetic operations on the pointer :++/–/+/-
hypothesis ptr It's a point to address 1000 Integer pointer to , It's a 32 An integer , Perform the following arithmetic operations on the pointer .ptr++
After performing the above operations ,ptr Will point to the position 1004, because ptr Every time you add , It will all point to the next integer position , That is, the current position moves back 4 Bytes . This operation will not affect the actual value of the memory location , Move the pointer to the next memory location . If ptr Point to an address for 1000 The characters of , The above operation will cause the pointer to point to the position 1001 The characters of , The above operation will cause the pointer to point to the position 1001, Because the next character is in 1001.
6.1: Increment a pointer
We like to use pointers instead of arrays in our programs , Because variable pointers can be incremented , The array cannot be incremented , An array can be treated as a pointer constant . The following program increments the variable pointer , In order to access each element of the array in sequence :
example :
#include <stdio.h>
const int MAX = 3;
int main(){
int var[] = {
10, 20, 30};
int i, *ptr;
ptr = var; // The address of the array in the pointer , The addressing character is not used here &
for(i=0; i<MAX; i++){
printf("address of var[%d] = %x \n", i, ptr);
printf("value of var[%d] = %d \n", i, *ptr);
ptr++; // Move to next location
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim dizeng_zhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc dizeng_zhizhen.c -o dizeng_zhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./dizeng_zhizhen
address of var[0] = 32e597f4
value of var[0] = 10
address of var[1] = 32e597f8
value of var[1] = 20
address of var[2] = 32e597fc
value of var[2] = 30
6.2: Decrement pointer
similarly , Decrement the pointer , That is, subtract the number of bytes of its data type from the value .
example :
#include <stdio.h>
const int MAX = 3;
int main(){
int var[] = {
10, 20, 30};
int i, *ptr;
ptr = &var[MAX -1]; // The address of the last element in the pointer , You need to use & Address character , Only the first element of the array , Don't use &
for(i=MAX; i>0; i--){
printf("address of var[%d] = %x \n", i, ptr);
printf("value of var[%d] = %d \n", i, *ptr);
ptr--; // Move to next location
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim dijian_zhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc dijian_zhizhen.c -o dijian_zhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./dijian_zhizhen
address of var[3] = 856862dc
value of var[3] = 30
address of var[2] = 856862d8
value of var[2] = 20
address of var[1] = 856862d4
value of var[1] = 10
6.3: The comparison of pointers
Pointers can be compared with relational operators , Such as ==、< and >. If p1 and p2 Point to two related variables , For example, different elements in the same array , Then you can p1 and p2 Make a size comparison .
The following program modifies the above example , As long as the address the variable pointer points to is less than or equal to the address of the last element of the array &var[MAX - 1], The variable pointer is incremented :
example :
#include <stdio.h>
const int MAX = 3;
int main(){
int var[] = {
10, 20, 30};
int i, *ptr;
ptr = var; // The address of the first element in the pointer
i = 0;
while(ptr <= &var[MAX - 1]){
printf("address of var[%d] = %x \n", i, ptr);
printf("value of var[%d] = %d \n", i, *ptr);
ptr++; // Point to the previous position
i++;
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim bijiao_zhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc bijiao_zhizhen.c -o bijiao_zhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./bijiao_zhizhen
address of var[0] = 79f125d4
value of var[0] = 10
address of var[1] = 79f125d8
value of var[1] = 20
address of var[2] = 79f125dc
value of var[2] = 30
7、 ... and : Pointer array
Before the concept of pointer arrays , Let's take a look at an example first , It uses a function of 3 An array of integers :
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {
10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}
When the above code is compiled and executed , It will produce the following results :
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation , We want the array store to point to int or char Or other data types . Here is a declaration of an array of pointers to integers :
int *ptr[MAX];
ad locum , hold ptr Declared as an array , from MAX An integer pointer makes up . therefore ,ptr Every element in , It's all a point int Pointer to value . The following example uses three integers , They will be stored in an array of pointers ,
As shown below :
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {
10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* Address assigned as an integer */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
When the above code is compiled and executed , It will produce the following results :
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to characters to store a list of strings , as follows :
#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed , It will produce the following results :
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
8、 ... and : The pointer to the pointer
It is a form of multilevel indirect addressing , Or a pointer chain . Usually , A pointer contains the address of a variable . When we define a pointer to a pointer , The first pointer contains the address of the second pointer , The second pointer points to the position containing the actual value .
Statement , Put two asterisks in front of the variable name :
int **var;
When a target value is indirectly pointed by one pointer to another , To access this value, you need to use two asterisk operators ,
example :
#include <stdio.h>
int main(){
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; // obtain var The address of
pptr = &ptr; // Use the operator & obtain ptr The address of
printf("var : %d \n", var);
printf("*ptr : %d \n", *ptr);
printf("**pptr : %d \n", **pptr);
printf("ptr: %x \n", ptr);
printf("pptr: %x \n", pptr);
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim zhizhenzhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc zhizhenzhizhen.c -o zhizhenzhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./zhizhenzhizhen
var : 3000
*ptr : 3000
**pptr : 3000
ptr: cc594804
pptr: cc5947f8
Nine : Passing pointers to functions
C Language allows you to pass pointers to functions , Simply declare the function parameter as a pointer type .
In the following example , We pass on an unsigned long Type pointer to function , And change the value in the function :
#include <stdio.h>
void getSeconds(unsigned long *par);
int main(){
unsigned long sec;
getSeconds(&sec);
printf("Number of seconds: %ld \n", sec); // Output actual value
return 0;
}
void getSeconds(unsigned long *par){
*par = time(NULL); // Get the current seconds
return;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim zhizhenhanshu.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc zhizhenhanshu.c -o zhizhenhanshu
zhizhenhanshu.c: In function ‘getSeconds’:
zhizhenhanshu.c:13:12: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
13 | *par = time(NULL); // Get the current seconds
| ^~~~
┌──(rootkali)-[~/Desktop/c_test]
└─# ./zhizhenhanshu
Number of seconds: 1655260682
Ten : Return pointer from function
In the last chapter , We already know C How to return an array from a function , Similarly ,C Allows you to return a pointer from a function . To do that , You must declare a function that returns a pointer , As shown below :
int * myFunction(){
}
in addition ,C Returning the address of a local variable outside of a function is not supported , Unless the local variable is defined as static Variable .
Now? , Let's look at the following function , Will generate 10 A random number , And use the array name that represents the pointer ( The address of the first array element ) To return them , As follows :
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// Functions to generate and return random numbers
int * getRandom(){
static int r[10];
int i;
srand((unsigned)time(NULL)); // Set seeds
for(i=0; i<10; ++i){
r[i] = rand();
printf("%d \n", r[i]);
}
return r;
}
// To call the main function of the function defined above
int main(){
// A pointer to an integer
int *p;
int i;
p = getRandom();
for(i=0; i<10; i++){
printf("*(p+[%d]) : %d\n", i, *(p+i));
}
return 0;
}
result :
┌──(rootkali)-[~/Desktop/c_test]
└─# vim hanshuzhizhen.c
┌──(rootkali)-[~/Desktop/c_test]
└─# gcc hanshuzhizhen.c -o hanshuzhizhen
┌──(rootkali)-[~/Desktop/c_test]
└─# ./hanshuzhizhen
1181024331
473861915
133589365
1181239576
862847673
808881362
1959669527
1283500003
1282139234
1969592223
*(p+[0]) : 1181024331
*(p+[1]) : 473861915
*(p+[2]) : 133589365
*(p+[3]) : 1181239576
*(p+[4]) : 862847673
*(p+[5]) : 808881362
*(p+[6]) : 1959669527
*(p+[7]) : 1283500003
*(p+[8]) : 1282139234
*(p+[9]) : 1969592223
边栏推荐
- 静态时序分析-OCV和time derate
- Nignx configuring single IP current limiting
- 第2章 关键技术介绍
- fplan-Powerplan实例
- Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal
- Knowledge of iPhone certificate structure
- PostgreSQL基础命令教程:创建新用户admin来访问PostgreSQL
- Semantic version 2.0.0
- Microservice system design -- Distributed timing service design
- 014 C语言基础:C字符串
猜你喜欢
![Basic functions of promise [IV. promise source code]](/img/a0/8f28ec8951088b8e66e7079432f326.png)
Basic functions of promise [IV. promise source code]

QChart笔记2: 添加鼠标悬停显示
![[BJDCTF2020]The mystery of ip](/img/f8/c3a7334252724635d42c8db3d1bbb0.png)
[BJDCTF2020]The mystery of ip

fplan-电源规划

Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal

Cultural tourism light show breaks the time and space constraints and shows the charm of night tour in the scenic spot

Microservice system design - service fusing and degradation design
![[BJDCTF2020]The mystery of ip](/img/f8/c3a7334252724635d42c8db3d1bbb0.png)
[BJDCTF2020]The mystery of ip

如何让 EF Core 6 支持 DateOnly 类型

Microservice system design -- message caching service design
随机推荐
MobileNet系列(4):MobileNetv3网络详解
Microservice system design - service fusing and degradation design
日志收集系統
halcon常用仿射变换算子
IOS development: understanding of dynamic library shared cache (dyld)
Why does C throw exceptions when accessing null fields?
微服务系统设计——消息缓存服务设计
Log collection system
日志收集系统
Method of decoding iPhone certificate file
面对AI人才培养的“产学研”鸿沟,昇腾AI如何做厚产业人才黑土地?
Usage knowledge of mobile phones in new fields
Cache comprehensive project - seckill architecture
Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
微服务系统设计——服务链路跟踪设计
PostgreSQL basic command tutorial: create a new user admin to access PostgreSQL
Promise [II. Promise source code] [detailed code comments / complete test cases]
021 C语言基础:递归,可变参数
跟着BUU学习Crypto(周更)
微服务系统设计——微服务调用设计