学习《C和指针》笔记

在看C和指针这本书的时候,第六章看到关于在列表中的字符串中查找一个特定的字符的两个版本,对版本二提到的会破坏指针数组的原因进行了分析,先上程序:

/* 版本一 */
#include 

#define TRUE    1
#define FALSE   0

int find_char( char **strings, char value )
{
    char * string;
    while ( ( string = *strings++ ) != NULL )
    {
        while ( *string != '\0' )
        {
            if ( *string++ == value )
                return TRUE;
        }
    }

    return FALSE;
}   

/* 版本二 */
#include 
#include 

#define TRUE    1
#define FALSE   0

int find_char( char **strings, int value )
{
    assert( strings != NULL );
    while ( *strings != NULL )
    {
        while ( **strings != '\0' )
        {
            if ( *(*strings)++ == value )
                return TRUE;
        }
        strings++
    }
    return FALSE;
}

char ** 是指向指针的指针,这这里看做是指针数组,数组中的元素是指向char的指针,而且都是指向各个字符串的首地址。
书中说版本二的程序会破坏这个指针数组,是由于*(*strings)++这个表达式中,(*strings)指向的是字符串的首地址,执行*(*strings)++的时候,++的优先级高于*,因此(*strings) 会先将它的值++,会使得(*strings)指向字符串的第二个元素,所以破坏了指针数组。

你可能感兴趣的:(C语言)