Original works, reproduced please indicate the source Http://blog.csdn.net/yming0221/article/details/7220688C language more viewC language Use Precautions (i)C language Use Precautions (ii)C language Use Precautions (iii)
The second-level pointer is also called a double pointer. There is no reference in the C language, so you must use a level two pointer when you try to change the value of a pointer. Reference types can be used in C + + to implement.
Here's how to use level two pointers in C.
For example, we use pointers to Exchange values for two integer variables.
The error code is as follows:
First-level pointers
[CPP]View Plaincopyprint?
- #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;
- }
#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 is structured as follows:
Results analysis: The parameters in the Swap function pass the constant value, regardless of the value or the pointer, so in the above function even if the address of A and B is passed to the swap function, the value of a and B is exchanged within the function (the address of A and B in the main function), and the exchange is complete. The corresponding arguments of the function are popped out of the stack and cannot be returned to the calling function, so the operation in the swap function is futile.
The values of A and B can be exchanged directly here, but if A and B are not a 32-bit integer variable, it is a complex data structure, which reduces efficiency. Following
[CPP]View Plaincopyprint?
- void Swap (TYPE *a,type *b)
- {
- TYPE tmp;
- Tmp=*a;
- *a=*b;
- *b=tmp;
- }
void swap (Type *a,type *b) { type tmp; Tmp=*a; *a=*b; *b=tmp;}
Second-level pointers
Here is an example of allocating memory using level two pointers
[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 value of a pointer consider using a two-dimensional pointer.
Level two pointer (double pointer) in C language