什么时候用指针的指针?如果你希望在一个函数的参数中改变一个指针的值,你就只能传这个指针的指针给这个函数。

  某个函数的功能是返回某个问题的计算结果,但是结果数据是不确定个数的值,所以在调用此函数时不知道事先应分配多少空间来保存返回的数据,此时的处理办法就是传递一个没有分配空间的指针的指针(地址)进去,让函数自己根据计算的结果分配足够的空间来保存结果,并返回,调用者使用了结果后,由调用者负责内存的释放,即,大家可能听说过的"谁使用(调用)谁释放"之类的话。

 
  
  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <stdbool.h> 
  4. #include <string.h> 
  5.  
  6. bool str_in(char **); 
  7. void str_sort(char *[],int); 
  8. void swap(char **p1,char **p2); 
  9. void str_out(char *[],int); 
  10.  
  11. const size_t BUFFER_LEN = 256; 
  12. const size_t NUM_P = 50; 
  13.  
  14. int main() 
  15.     char *pS[NUM_P] = {NULL}; 
  16.     int count = 0; 
  17.      
  18.     printf("\nEnter successive lines,pressing Enter at the end of" 
  19.            "each line.\nJust press Enter end.\n"); 
  20.      
  21.     for(count = 0;count < NUM_P;count++) 
  22.        if(!str_in(&pS[count])) 
  23.        break
  24.         
  25.     str_sort(pS,count); 
  26.     str_out(pS,count); 
  27.      
  28.     system("pause"); 
  29.     return 0; 
  30.  
  31. bool str_in(char **pString) 
  32.      char buffer[BUFFER_LEN]; 
  33.       
  34.      if(gets(buffer) == NULL) //将输入读入buffer中,如果读取输入时发生错误,该函数就返回NULL,所以需要先检查NULL  
  35.      { 
  36.         printf("\nError reading string.\n"); 
  37.         exit(1); 
  38.      } 
  39.       
  40.      if(buffer[0] == '\0'
  41.        return false
  42.         
  43.      *pString = (char *)malloc(strlen(buffer) + 1); 
  44.       
  45.      if(*pString == NULL)  //判断内存是否足够分配  
  46.      { 
  47.        printf("\nOut of memory."); 
  48.        exit(1); 
  49.      } 
  50.       
  51.      strcpy(*pString,buffer); 
  52.      return true
  53.  
  54. void str_sort(char *p[],int n) 
  55.      char *pTemp = NULL; 
  56.      bool sorted = false
  57.       
  58.      while(!sorted) 
  59.      { 
  60.         sorted = true
  61.         for(int i = 0;i < n-1;i++) 
  62.           if(strcmp(p[i],p[i + i]) > 0) 
  63.           { 
  64.               sorted = false
  65.               swap(&p[i],&p[i+1]); 
  66.           } 
  67.      } 
  68.  
  69.  
  70. void swap(char **p1,char **p2) 
  71.      char *pt = *p1; 
  72.      *p1 = *p2; 
  73.      *p2 = pt; //指针必须同级  
  74.  
  75.  
  76. void str_out(char *p[],int n) 
  77.      printf("\nYour input sorted in order is :\n\n"); 
  78.      for(int i = 0;i < n;i++) 
  79.      { 
  80.          printf("%s\n",p[i]); 
  81.          free(p[i]); 
  82.          p[i] = NULL; 
  83.      } 
  84.      return

   以上代码出自:《C语言入门经典》,略有改动。