Level 2 pointer (double pointer) in C Language
For original works, refer to the source for reprinting (1) Notes for using C language (2) Notes for using C language (3)
A second-level pointer is also called a double pointer. There is no reference in C language, so when you try to change the value of a pointer, you must use a second-level pointer. The reference type can be used in C ++.
The following describes how to use the second-level pointer in C.
For example, we use pointers to exchange the values of Two integer variables.
The error code is as follows:
Level 1 pointer
[Cpp]View plaincopyprint?
- # Include <stdio. h>
- Void swap (int * a, int * B)
- {
- Int * tmp = NULL;
- Tmp =;
- A = B;
- B = tmp;
- }
- Int main (int argc, char ** argv)
- {
- Int a = 2;
- Int B = 3;
- Printf ("Before swap a = % d B = % d \ n", a, B );
- Swap (& a, & B );
- Printf ("After swap a = % d B = % d \ n", a, B );
- Return 0;
- }
#include <stdio.h>void swap(int *a,int *b){ int *tmp=NULL; tmp=a; a=b; b=tmp;}int main(int argc,char **argv){ int a=2; int b=3; printf("Before swap a=%d b=%d\n",a,b); swap(&a,&b); printf("After swap a=%d b=%d\n",a,b); return 0;}
The output structure is as follows:
Result Analysis: no matter the value or pointer, the parameters in the swap function always pass the value. Therefore, even if the addresses a and B have already passed the parameters to the swap function, in the function, the values of a and B are exchanged (the address of a in the main function and the address of B). After the switching, the corresponding parameters of the function pop up from the stack, it cannot be returned to the called function, so the operations in the swap function are futile.
The values of a and B can be directly exchanged here. However, if a and B are not a 32-bit integer variable but a complex data structure, this will reduce the efficiency. As follows;
[Cpp]View plaincopyprint?
- Void swap (TYPE * a, TYPE * B)
- {
- TYPE tmp;
- Tmp = *;
- * A = * B;
- * B = tmp;
- }
void swap(TYPE *a,TYPE *b){ TYPE tmp; tmp=*a; *a=*b; *b=tmp;}
Level 2 pointer
The following is an example of using a second-level pointer to allocate memory.
[Cpp]View plaincopyprint?
- # Include <stdio. h>
- # Include <stdlib. h>
- # Include <string. h>
- Void memorylocate (char ** ptr)
- {
- * Ptr = (char *) malloc (10 * sizeof (char ));
- }
- Int main (int argc, char ** argv)
- {
- Char * buffer;
- Memorylocate (& buffer );
- Strcpy (buffer, "12345 ");
- Printf ("buffer % s \ n", buffer );
- Return 0;
- }
#include <stdio.h>#include <stdlib.h>#include <string.h>void memorylocate(char **ptr){ *ptr=(char *)malloc(10*sizeof(char));}int main(int argc,char **argv){ char *buffer; memorylocate(&buffer); strcpy(buffer,"12345"); printf("buffer %s\n",buffer); return 0;}
When you want to change the pointer value, consider using a two-dimensional pointer.