C language - first understanding of pointers

0. Preface

Pointers can be said to be a difficult point for beginners to learn C language, and pointers are also an important knowledge point in C language. Let's take a closer look at what a pointer is.

1. What exactly is a pointer?

The pointers we usually talk about are actually called pointer variables, which are variables used to store addresses. Here is an example:

int a = 10;
int* p = &a;
printf("%p\n",&a);//结果000000000062FE14
printf("%p\n",p); //结果000000000062FE14

It can be found that the address of p is the address of a. It can be understood that p = &a  takes the address of a and passes it to p.

The int of int* p is because our a variable is of type int. Similarly, there are char* double*... (defined according to the variable type).

If the address is compared to the house number, then the * number is the key to open the room. Example of the code just now:

	int a = 10;
	int* p = &a;
	printf("%p\n",&a);//结果:000000000062FE14
	printf("%p\n",p); //结果:000000000062FE14
	printf("%d",*p);  //结果:10

2. Arrays seem to have something to do with pointers?

 int arr[10] = {1,2,3,4,5,6,7,8,9,0};
    printf("%d\n", *arr);   //结果:1
    printf("%p\n", arr);    //结果:000000000062FDF0
    printf("%p\n", &arr[0]);//结果:000000000062FDF0

We were pleasantly surprised to find that the address of the array name is the address of the first element of the array . Then explore again:

 int arr[10] = {1,2,3,4,5,6,7,8,9,0};
    printf("%d\n", *(arr+0));//结果:1 == arr[0]
    printf("%d\n", *(arr+1));//结果:2 == arr[1]
    printf("%d\n", *(arr+2));//结果:3 == arr[2]
    printf("%d\n", *(arr+3));//结果:4 == arr[3]
    printf("%d\n", *(arr+4));//结果:5 == arr[4]
    printf("%d\n", *(arr+5));//结果:6 == arr[5]
    printf("%d\n", *(arr+6));//结果:7 == arr[6]
    printf("%d\n", *(arr+7));//结果:8 == arr[7]
    printf("%d\n", *(arr+8));//结果:9 == arr[8]
    printf("%d\n", *(arr+9));//结果:0 == arr[9]

In fact, after +1 to the address of the first element of the array, it becomes the address of the second element of the array . and so on.

Guess you like

Origin blog.csdn.net/m0_74358683/article/details/130296127