Advanced Pointers - 1 (In-depth understanding of C language)

1. Basic concepts of pointers

1.1 Review the basic concepts of pointers:

A pointer is a variable used to store an address. The address uniquely identifies a memory space.
The size of the pointer is fixed 4/8 bytes (32-bit platform/64-bit platform).
Pointers have types. The type of the pointer determines the ±integer step size of the pointer and the permissions during the pointer dereference operation.

2. Character pointer

Among the types of pointers, we know that there is a pointer type called character pointer char *

As the name suggests, a character pointer refers to a pointer to a string .

A string is an array of characters, each character occupies one byte .

Character pointers can be used to access each character of a string, or to traverse the entire string through pointer arithmetic. Common string operations require the use of character pointers, such as string copying, comparison, concatenation, etc. In C language, the string ends with the null character '\0' , so when using the character pointer to operate the string, you need to pay attention to the position of the null character .

Note: The string pointed to by the character pointer is called a constant string because in most programming languages, string constants are not modifiable. This means that once a string constant is defined, its contents cannot be modified directly.

2.1 Character pointers are generally used like this:

int main()
{
    
    
 char ch = 'w';
 char *pc = &ch;
 *pc='w';
 *pc = "abcdef";//一般这种常量字符串前面最好加上一个const修饰它,让它不能被修改
 return 0;
}

Insert image description here

2.2 After we understand the above example, let’s take a look at the following interview question: (This question comes from "Sword Finger Offer")

#include <stdio.h>
int main()
{
    
    
 char str1[] = "hello bit.";
 char str2[] = "hello bit.";
 const char *str3 = "hello bit.";
 const char *str4 = "hello bit.";
 if(str1 ==str2)
 printf("str1 and str2 are same\n");
 else
 printf("str1 and str2 are not same\n");
 
 if(str3 ==str4)
 printf("str3 and str4 are same\n");
 else
 printf("str3 and str4 are not same\n");
 
 return 0;
}

The final output here is:
Insert image description here
Because the array name represents the address of the array element (except & (array name) and sizeof (array name)),
it is not difficult to see in this question that str1, str2, str3, and str4 all represent the address of the first element of the array.

Here str3 and str4 point to the same constant string. Constant strings are not allowed to be modified. C/C++ will store constant strings in a separate memory area. When several pointers point to the same constant string, they will actually point to the same memory.

But when using the same constant string to initialize different arrays,
different memory blocks will be allocated. So str1 and str2 are different, str3 and str4 are the same.

The diagram is as follows:
Insert image description here

3. Pointer array

We know that:
an integer array is an array that stores integers;
a character array is an array that stores characters;
by analogy, a pointer array is an array that stores pointers. Each element in the pointer array is a pointer to a certain data type.

Each element in this array can point to a different memory address, so arrays of pointers can be used to achieve polymorphism.

The definition of an array pointer is: data type * array variable name [array length] .

3.1 Related examples of pointer arrays:

#include <stdio.h>
int main()
{
    
    
	int arr1[] = {
    
     1,2,3,4,5 };
	int arr2[] = {
    
     2,3,4,5,6 };
	int arr3[] = {
    
     3,4,5,6,7 };
	//指针数组
	int* parr[3] = {
    
     arr1,arr2,arr3 };
	//存放字符指针的数组
	char *ch[]={
    
    0};
	return 0;
}

Insert image description here

4. Array pointer

By analogy with the character pointer above, we can see that an array pointer is a pointer variable pointing to an array, which can also be called a reference pointing to an array. It can point to the starting address of the array, which is the address of the first element of the array, so that each element of the array can be accessed through a pointer.

The definition of an array pointer is: data type (*pointer variable name) [array length] .

Among them, the pointer variable name is the name of a pointer variable, the data type is the type of the elements in the array, and the array length is the number of elements in the array.

The array can be traversed, read and modified through the array pointer. It should be noted that the array pointer is not an array, it is just a pointer variable pointing to the array, so it does not have the attributes of the array, such as length, size, etc.

4.1 Which of the following codes is an array pointer?

int *p1[10];
int (*p2)[10];
//p1, p2分别是什么?

p1 is an array capable of storing 10 integer pointers;

p2 is first combined with, indicating that p is a pointer variable, and then points to an array of size 10 integers. So p2 is a pointer, pointing
to an array, called an array pointer.
Note here: [] has a higher priority than
number, so () must be added to ensure that p is combined with * first.

4.2 &Array name VS array name

For the following array:

int arr[10];

What are arr and &arr?
We know that arr is the array name, and the array name represents the address of the first element of the array.
So what exactly is the &arr array name?

Let's look at a piece of code:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
    0};
 printf("%p\n", arr);
 printf("%p\n", &arr);
 return 0;
}

The running results are as follows:
Insert image description here
It can be seen that the address printed by the array name and &array name is the same.
Are the two the same?
Let’s look at another piece of code:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
     0 };
 printf("arr = %p\n", arr);
 printf("&arr= %p\n", &arr);
 printf("arr+1 = %p\n", arr+1);
 printf("&arr+1= %p\n", &arr+1);
 return 0;
}

The running results are as follows:
Insert image description here
According to the above code, we found that in fact, although the values ​​​​of &arr and arr are the same, their meanings should be different.
In fact: &arr represents the address of the array, not the address of the first element of the array. (Think about it carefully)
The type of &arr in this example is: int(*)[10], which is the address of an array pointer type
array + 1, skipping the size of the entire array, so the difference between &arr+1 and &arr value is 40


The array name generally represents the address of the first element of the array, but there are two exceptions:
1.&(array name) takes the address of the entire array
2.sizeof(array name) calculates the size of the entire array


4.3 Use of array pointers

How are array pointers used?
Since the array pointer points to an array, the address of the array should be stored in the array pointer.
Look at the code:

#include <stdio.h>
int main()
{
    
    
 int arr[10] = {
    
    1,2,3,4,5,6,7,8,9,0};
 int (*p)[10] = &arr;//把数组arr的地址赋值给数组指针变量p
 //但是我们一般很少这样写代码
 return 0;
}

The use of an array pointer: ( This is just a simple example to explain the array pointer. The advantage of the array pointer may only be reflected in complex code )

#include <stdio.h>
void print_arr1(int arr[3][5], int row, int col)
{
    
    
 	int i = 0;
 	for(i=0; i<row; i++)
 	{
    
    
 		for(j=0; j<col; j++)
 		{
    
    
 			printf("%d ", arr[i][j]);
 		}
 		printf("\n");
 	}
}
void print_arr2(int (*arr)[5], int row, int col)
{
    
    
 	int i = 0;
 	for(i=0; i<row; i++)
 	{
    
    
 		for(j=0; j<col; j++)
 		{
    
    
 			printf("%d ", arr[i][j]);
 		}
 		printf("\n");
 	}
}
int main()
{
    
    
 int arr[3][5] = {
    
    1,2,3,4,5,6,7,8,9,10};
 print_arr1(arr, 3, 5);
 //数组名arr,表示首元素的地址
 //但是二维数组的首元素是二维数组的第一行
 //所以这里传递的arr,其实相当于第一行的地址,是一维数组的地址
 //可以数组指针来接收
 print_arr2(arr, 3, 5);
 return 0;
}

After learning about pointer arrays and array pointers, let’s review them together and see what the following code means:

int arr[5];
int *parr1[10];
int (*parr2)[10];
int (*parr3[10])[5];

Insert image description here

Guess you like

Origin blog.csdn.net/originalHSL/article/details/131586407