指向指针的指针的用途

来源:互联网 发布:heyden 分层标定算法 编辑:程序博客网 时间:2024/06/12 01:06
             在阅读apache的源码时,发现一处使用指针的指针的案例,平时没有够多考虑指向指针的指针这个问题,今天顺便理解了一下,这里沾上apache的源码,这时apr一个很经常用的函数,就是根据字符串的中断值来获取中断值隔开的字符串,比如“T=0&L=1&X=2&Y=3”,这个函数可以通过‘&’来获取T L X Y的值,它会将开始的字符串地址输入str,中断值输入为sep,last是中断值后面字符串开始的地址,获取每个中断值隔开的字符串后,将中断值所在的位置设为‘/0’,这样取走每一个字符串,每取走一个字符串就将中断值后面的字符串起始地址传给last,这样一个一个的获取所有的字符串,但是这里的last为什么是指向指针的指针呢?下面是函数源码。
APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last){    char *token;    if (!str)           /* subsequent call */        str = *last;    /* start where we left off */    /* skip characters in sep (will terminate at '\0') */    while (*str && strchr(sep, *str))        ++str;    if (!*str)          /* no more tokens */        return NULL;    token = str;    /* skip valid token characters to terminate token and     * prepare for the next call (will terminate at '\0)      */    *last = token + 1;    while (**last && !strchr(sep, **last))        ++*last;    if (**last) {        **last = '\0';        ++*last;    }    return token;}

调用代码

            for(pair = apr_strtok(p+4,delim,&last);pair != NULL;                pair = apr_strtok(NULL,delim,&last))
       将last设置为指向指针的指针的原因是,如果传入的指针,那么只是一个副本,这个指针改变了并不能改变外部调用的指针的地址,如果是指向指针的指针,那么*last即字符串的地址改变了之后,相当于改变了last指向的内容,last不变,但他指向的内容即字符串的地址改变了,这样指向字符串的值也就变了,达到了目的。


原创粉丝点击