《C和指针》的107页 程序6.3 在一组字符串中查找:版本2
程序如下:
#include <stdio.h>
#include <assert.h>
#define TRUE 1
#define FALSE 0
int find_char(char **strings, char value) // 1
{
assert(strings != NULL);
while (*strings != NULL) // 2
{
while (**strings != '\0') // 3
{
if (*(*strings)++ == value) // 4
{
return TRUE;
}
}
strings++; // 5
}
return FALSE;
}
int main()
{
char string1[] = "abcd"; //6
char string2[] = "defg";
char string3[] = "love";
char* strings[] = { string1, string2, string3, 0 };
if (find_char(strings, '1') == TRUE)
{
printf("yes\n");
}
else
{
printf("no\n");
}
printf("%d\n", num);
return 0;
}
// 1 int find_char(char **strings, char value)
函数的第一个参数是 ==char **strings==
首先,因为输入参数并不是一个字符串,一个知足字符串。那么他们是怎么存放的呢?如 ==//6== 及以下几行所示,其将每个字符串都存放在数组中,此时,数组名代表了字符串的第一个字符的首地址,及数组名为char*类型。而strings是一个存放字符地址的数组,数组名表示char地址的地址,所以其类型为char**类型 。
// 2 while (*strings != NULL)
此while循环用于遍历字符数组。
strings为存放字符数组的数组的数组名,加上*表示第一个元素,也就是其中存储的字符数组。若第一个元素不为空说明还有字符数组,此举用来判断strings数组是否为空,也就是什么时候跳出循环
// 3 while (**strings != '\0')
strings加上*表示第一个元素,也就是其中存储的字符数组,那么**strings就表示strings中存储的第一个字符数组的第一个字符。若其为'\n',则说明该字符数组已经遍历完毕。
// 4 if (*(*strings)++ == value)
该句可以分解为如下语句:
if (**strings == value)
{
}
(*strings)++
于括号的存在,需要先计算括号内的内容,即*strings,也就是第一个strings内存放的第一个字符数组的首地址。然后在计算自增。由于四后置++,所以前面*修饰的相当于是*strings,也就是说去出了字符数组中的第一个字符,然后在查看之后,在将数组名指向下一位,达到读取下一位的目的。
// 5 strings++
当跳出while (**strings != '\0')循环的时候,说明第一个字符数组已经遍历完成,该遍历下一个字符数组了。需要将strings指向下一个字符数组