Explain the operation of pointer in detail

When our program is running, the pointer exists all the time and is used all the time. It points to the corresponding data in the memory.

Usually, if a piece of data is stored sequentially, the pointer operation will be particularly important. Here we carefully analyze the pointer operation.

1. Pointer plus and minus numbers

Let's look at the following example, what is the addition of pointers like?

int a = 0x0000000000000001 + 1;    //指针的本质其实就一个16进制的无符号整形
printf("%d\n", a);
int arr[10];      //数组名只有在sizeof和&时才会代表整个数组,否则都是代表首元素地址
printf("%p %p\n", arr, arr + 1); //这里的结果又是什么呢?

Here we analyze:

int a = 0x0000000000000001 + 1 why is it equal to 2?

Because here is actually not adding a pointer to an integer, but adding two integers, 0x0000000000000001 is actually 1, 1+1=2.

Look at the arr array below, the address difference between arr and arr+1 is 4 bytes, but I only have "+1"?

This is because the addition and subtraction of pointers will automatically add or subtract 1 type length according to your type, because we define an integer array, and the integer occupies 4 bytes, so the "+1" in arr+1 here represents is to add an integer length.

The subtraction of pointers is the same as addition, and the subtraction of arrays by pointers also subtracts the length of its type.

 1. Add and subtract pointers

First of all, it is meaningless to add pointers to pointers, it is meaningful to subtract

The compiler will report an error when the pointer is added directly, so we have verified that the addition of pointers is meaningless.

So what's the point of subtracting pointers?

The subtraction of pointers can calculate the number of type elements that differ between two addresses in a string of continuous type data.

 Note: If it is not a series of continuous data of the same type, the subtraction of pointers is meaningless! ! !

Guess you like

Origin blog.csdn.net/fengjunziya/article/details/130463795