Pointer of C language learning notes (the soul of C language)

1. Introduction of problems
int a;// Defines a variable a of type int, which essentially allocates a 4-byte memory unit
a = 100;// Store the value 100 in the storage unit corresponding to variable a
b = a;// Take out the value of variable a and store it in the storage unit corresponding to variable B.

===> stay C In language, any variable name has two meanings:
	(1)Represents the storage unit of the variable        Lvalue(lvalue)
	(2)Represents the value of the variable              Right value(rvalue)
Moreover, there are only two cases when we access variables:
	(1)Store a value in the storage space of a variable  (write)
	(2)Value from the storage space of the variable          (read)
We know that the system has associated the variable name with the address of the variable, and the system is essentially connected through the address
 To access a variable. So, someone asked, can we also access variables directly through addresses?
===> Pointer

2. The concept of pointer
Address: the system divides the memory into many copies in a byte for numbering. This number is
Address in memory unit.
In C language, the concept of pointer is similar to that of address. You can think of pointer as a typed address.

The first address of a variable is called the address of the variable"Pointer". It indicates where the content of the variable starts.

3. Pointer variable
★ pointer variable is also a variable, which is used to save the address of an object.

Definition of pointer variable:
	type   *Pointer variable name;
	"type": The type that the pointer variable points to
	"point": If I keep your address, then I point to you
	 int a;
	 int *p;//Defines a pointer variable p of type int*
     p = &a;//p is a pointer variable name, and the type it points to is int	

Note: in 32-bit processors, the addresses are all 32 bits, that is, the space allocated by pointer variables is 4 bytes,
	  Therefore, the forced conversion of pointer variables to other types of pointer types will not be distorted.
	  therefore void* Also called universal pointer.
★The type of pointer variable determines the operation between the pointer variable and integer data, so that its actual address changes
  Magnification relationship.
eg:  int a;
		     char b;
			 int *p1 = &a;
			 char *p2 = &b;

4. How to get the address
(1) By taking the address character&
&Object name: indicates the address of the object
Objects: variables, array elements...
(2) Some object names themselves represent addresses
For example: array name, function name...
Note: the addresses obtained by these two methods are of different types.

5. How to access the space pointed to by the pointer: * (pointing to the operator)
(address) < = = > the variable corresponding to the address
That is, (address) can also be used as left and right values, and the address can also be taken
*&a <==> a
*&You can make a direct appointment

be careful: To be associated with the multiplication operator and when defined*Phase difference
	int *p,a=3;
	p = &a;

6. Array and pointer
Like ordinary variables, array elements also have their own addresses.
And the addresses between array elements are continuous, and the array name is the first address of the array.
eg: int a[10];
int *p;
p = &a[0];
Assign 100 as a[0]. How many ways can you write it
a[0] = 100;
*p = 100;
*a = 100;// The array name is the first address of the array (the address of the first element)

	that *(a+1) ==> a[1]
★ *(p+i) <=> p[i],when i>=0

7. Two dimensional array and pointer
int a[3][4];
The two-dimensional array a can be regarded as a one-dimensional array whose element is int[4],
Therefore, * (a + I) < = > a [i] points to the ith element of the one-dimensional array, which is of type int[4].
Therefore, you need to point again to point to the elements of the two-dimensional array:
((a + I) + J) < = = > a [i] [J], the element type is int.

expression(i>=0,j>=0)     		type/sizeof              meaning                     value
a+i	              		int[4]*/int[3][4](No, i) Point to No i First address of line            &a[i]
*(a+i)+j<=>a[i]+j       int*/ int[4](No, j)      The first i Line number j The address of the element of the column       &a[i][j]
*(*(a+i)+j)<=>a[i][j]       int                  The first i Line number j Elements of columns             a[i][j]
	 char a[3]={'a','b','c'};
	 char b[2][3]={{'1','2','3'},{'4','5','\0'}};
	 printf("%ld %ld %c\n",sizeof(a),sizeof(a+1),*(a+1));//3 8 b
	 printf("%ld %ld %ld %s\n",sizeof(b),sizeof(b+1),sizeof(*(b+1)),*(b+1));//6 8 3 45

8. String and pointer
In C language, there is no built-in string type. C language string is realized through char * pointer.

char *str = "ABCDEF";//Assign the first address of the string stored in the rodata section to str
char str1[]="ABCDEF";//Define a character array and initialize its contents to "ABCDEF"

	str: Save the first address of the string, that is, the character'A'Your address.
	str+1: Pointing character'B'Your address.
*(str+1) = '2';//error, because there is no character array defined here and no space allocated,
               //Constants are stored in the rodata section and cannot be changed
*(str1+1)= '2';//right

"ABCDEF"stay C In language, the first address of the string is assigned to str,Because the string must have a terminator,
The system can completely access the contents of the string.

9. Null pointer and wild pointer

(1)NULL Also called null pointer, it is actually the first macro defined by the system, indicating that it does not point to any space.
		#define  NULL ((void*)0)
		therefore NULL Represents a false in a logical operation
		NULL Cannot be accessed, otherwise a segment error will be reported.
(2)Field pointer
	Wild pointer is not NULL Pointer, but a pointer to illegally allocated space
		There are two causes of wild pointer
		1)Pointer variable not initialized
		2)Pointer variable is free or delete Not set as NULL,People mistakenly think p It's also a legal pointer
	(1) void swap(int *a,int *b)//error
			int *p;//p is a wild pointer
			*p = *a;
			*a = *b;
			*b = *p;
		char *p = (char*)malloc(100);//Allocate 100 bytes of space in the dynamic memory area
		free(p);//The allocated space has been released
		if( p!= NULL)

11. Array pointer and pointer array
int a[10];// Defines an array a with 10 elements, each of which is of type int
If we want to define a pointer p to hold the address of A.
How to define?

typeof(a)  *p;
==> int[10] *p;
==> int (*p)[10];
	p Is a pointer to an array(int[10]),So let's put p It's called an array pointer
 because'*'The combination of is low, so we should put it here(*p),Indicates that the definition is a pointer.
★The two-dimensional array name is an array pointer, so the usage of array pointer is the usage of two-dimensional array name.

int *p[10];
there p Is an array with 10 elements, each of which is int *Type,
So let's put p It's called a pointer array.

eg:  int (*p1)[10];//Defines an array pointer variable
     int *p2[10];//Defines an array of pointers
	 printf("%d %d\n",sizeof(p1),sizeof(p2));//8  80

12. Parameters of main
Under unix/linux, the prototype of main function should be as follows:
int main(int argc, char *argv[])
When the operating system calls your executable program (calling your main function), it is allowed to take parameters,
Only these parameters are of string type (char *)
argc: argument count indicates the number of parameters (program name, also a parameter) when running your program
argv: argument vector parameter is an array of string pointers
eg: ./a.out 1 2

13. Two level pointer and multi-level pointer
In fact, the main function prototype can also be written as the following pattern
int main(int argc, char **argv)

The visible pointer array is a secondary pointer
 A secondary pointer is a pointer that can point to twice. Generally, there are two ways to understand it
(1) Address of pointer variable
	eg:  int a=100;
	     int *p = &a;
		 int **p2 = &p;//p2 is a secondary pointer variable, and its type is int**
		 printf("%d %d %d\n",a,*p,**p2);
(2)Pointer array
	If the element of an array is a pointer, the array name is a secondary pointer.
	Similarly, if the element of an array is a secondary pointer, the array name is a tertiary pointer.

	stay C In language,char *Can represent a string. In fact, a pointer can also represent a defined array.
	The difference is that the string has a terminator'\0'To determine the length, and the array must be given its own length.

14. Function pointer
The function pointer variable is the variable used to save the function address.
Definition of function pointer variable:
The return value type of the function pointed to (* function pointer variable name) (the function parameter list pointed to);

Call the function pointed to through the function pointer:
	(*Function pointer)(Argument list)
	(Function pointer)(Argument list)
Usage of function pointers:
	1)Thread pool
	2)Callback function

A callback function is a function that is passed as a parameter.
The user passes the pointer of the function to be called as a parameter to a function, so that the function can flexibly use different parameters when dealing with corresponding events
Application example:General operating systems have implemented the interrupt mechanism, but users can not directly define the interrupt processing function, and can only call it in the interrupt processing function
 User defined callback function.
☆Function pointer array
	void (*a[3])(int,int);//A function pointer array A is defined. It has three elements, and each element is a function pointer
	                      //Function pointer with return value of void and parameter type of (int,int).

15. Pointer as function parameter
Since the formal parameter cannot change the value of the argument, the called function usually uses return to pass data to the calling function.
In addition, there are two ways:
(1) Accessing global variables
(2) With pointer as function parameter

16. Dynamic memory allocation
malloc free realloc calloc

malloc, free, calloc, realloc - allocate and free dynamic memory

#include <stdlib.h>

malloc: memory allocate,A dynamic memory area used to store data in a process(heap)Allocate a piece of memory,
		And the first address of the allocated memory is returned as the return value of the function.
		"Dynamic memory area of the process":It is also a memory area, but the memory lifetime of the area
		Is continuous with the process. Once assigned, if not manually released(free),Then it exists until the process exits.
   void *malloc(size_t size);
		@size: The size of dynamic memory you want to allocate, in bytes
		Return value:
			If successful, the first address of the allocated space will be returned
			If failed, return NULL
free: Used to release malloc/calloc Requested dynamic memory area
   void free(void *ptr);
		@ptr: You want to free the first address of that memory(malloc/calloc Return value of)
calloc It is used to allocate a memory space for storing arrays 
   calloc(n,size) <==>  malloc(n*size);
   void *calloc(size_t nmemb, size_t size);
		@nmemb : Number of array elements
		@size : How many bytes does each element occupy
		Return value:
			If successful, the first address of the allocated space will be returned
			If failed, return NULL
realloc: repeat allocate
	1) change ptr The size of the segment of dynamic memory pointed to
		ptr The contents of the original memory space pointed to remain unchanged, and the increased and reduced memory will not be initialized.
	2) If ptr == NULL
		that realloc(NULL,size) <==> malloc(size)
	3) If ptr!=NULL,And size==0
	    that realloc(ptr,0) <==>  free(ptr)
   void *realloc(void *ptr, size_t size);

Tags: C C++ R Language

Posted on Wed, 22 Sep 2021 12:30:29 -0400 by jagguy