什么时候用指针的指针?如果你希望在一个函数的参数中改变一个指针的值,你就只能传这个指针的指针给这个函数。
某个函数的功能是返回某个问题的计算结果,但是结果数据是不确定个数的值,所以在调用此函数时不知道事先应分配多少空间来保存返回的数据,此时的处理办法就是传递一个没有分配空间的指针的指针(地址)进去,让函数自己根据计算的结果分配足够的空间来保存结果,并返回,调用者使用了结果后,由调用者负责内存的释放,即,大家可能听说过的"谁使用(调用)谁释放"之类的话。
- #include <stdlib.h>
- #include <stdio.h>
- #include <stdbool.h>
- #include <string.h>
- bool str_in(char **);
- void str_sort(char *[],int);
- void swap(char **p1,char **p2);
- void str_out(char *[],int);
- const size_t BUFFER_LEN = 256;
- const size_t NUM_P = 50;
- int main()
- {
- char *pS[NUM_P] = {NULL};
- int count = 0;
- printf("\nEnter successive lines,pressing Enter at the end of"
- "each line.\nJust press Enter end.\n");
- for(count = 0;count < NUM_P;count++)
- if(!str_in(&pS[count]))
- break;
- str_sort(pS,count);
- str_out(pS,count);
- system("pause");
- return 0;
- }
- bool str_in(char **pString)
- {
- char buffer[BUFFER_LEN];
- if(gets(buffer) == NULL) //将输入读入buffer中,如果读取输入时发生错误,该函数就返回NULL,所以需要先检查NULL
- {
- printf("\nError reading string.\n");
- exit(1);
- }
- if(buffer[0] == '\0')
- return false;
- *pString = (char *)malloc(strlen(buffer) + 1);
- if(*pString == NULL) //判断内存是否足够分配
- {
- printf("\nOut of memory.");
- exit(1);
- }
- strcpy(*pString,buffer);
- return true;
- }
- void str_sort(char *p[],int n)
- {
- char *pTemp = NULL;
- bool sorted = false;
- while(!sorted)
- {
- sorted = true;
- for(int i = 0;i < n-1;i++)
- if(strcmp(p[i],p[i + i]) > 0)
- {
- sorted = false;
- swap(&p[i],&p[i+1]);
- }
- }
- }
- void swap(char **p1,char **p2)
- {
- char *pt = *p1;
- *p1 = *p2;
- *p2 = pt; //指针必须同级
- }
- void str_out(char *p[],int n)
- {
- printf("\nYour input sorted in order is :\n\n");
- for(int i = 0;i < n;i++)
- {
- printf("%s\n",p[i]);
- free(p[i]);
- p[i] = NULL;
- }
- return;
- }
以上代码出自:《C语言入门经典》,略有改动。
转载于:https://blog.51cto.com/zoufuxing/697699