Original works, reprint please indicate the source http://blog.csdn.net/yming0221/article/details/7220688 C language more see C language use attention (i) C language use notice (b) C language use attention (iii)
Second-level pointers are also called double pointers. 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 the values of two integer variables.
The error code is as follows:
First-level pointers
#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:
Result Analysis: Whether the value or the pointer, the arguments in the SWAP function pass the constant value, so even if the address of A and B is passed to the swap function in the above function, the value of a and B is exchanged within the function (the address of A and B in the main function), and the swap is complete. The corresponding parameter of the function pops out of the stack and cannot be returned to the calling function, so the operation in the swap is futile.
It's perfectly possible to exchange A and B values directly, but if A and B are not a 32-bit integer variable, but rather a complex data structure, this can reduce efficiency. Following
void swap (Type *a,type *b)
{
type tmp;
Tmp=*a;
*a=*b;
*b=tmp;
}
Second-level pointers
The following is an example of allocating memory using level two pointers
#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;
}
Consider using a two-dimensional pointer when you want to change the value of a pointer.