关于 搜索字符 函数 是否会破坏指针 数组
搜索字符串里的字符:
版本一:
- C/C++ code
/*** Given a pointer to a NULL-terminated list of pointers, search** the strings in the list for a particular character.*/#include <stdio.h>#define TRUE 1#define FALSE 0intfind_char( char **strings, char value ){ char *string; /* the string we're looking at */ /* ** For each string in the list ... */ while( ( string = *strings++ ) != NULL ){ /* ** Look at each character in the string to see if ** it is the one we want. */ while( *string != '\0' ){ if( *string++ == value ) return TRUE; } } return FALSE;}
版本二:
- C/C++ code
/*** Given a pointer to a NULL-terminated list of pointers, search** the strings in the list for a particular character. This** version destroys the pointers so it can only be used when** the collection will be examined only once.*/#include <stdio.h>#include <assert.h>#define TRUE 1#define FALSE 0intfind_char( char **strings, int value ){ assert( strings != NULL ); /* ** For each string in the list ... */ while( *strings != NULL ){ /* ** Look at each character in the string to see if ** it is the one we want. */ while( **strings != '\0' ){ if( *(*strings)++ == value ) return TRUE; } strings++; } return FALSE;}
书上说 版本二虽然比版本一方便些,
但是版本二只能进行一次搜寻,因为他会破坏指针数组.
那是因为 *(*strings)++ 的副作用么? 判断最后一个非'\0' 字符, 依然自增 ? 真是不理解.
如果这么说. 那么在版本一中 :*strings++ 在指向最后一个指针后,也需要再自增,指向下一个指针. 那不也是破坏了指针数组 ?
新年快乐 :)
[解决办法]
第二种方法破坏数组是因为最后进行了strings++操作,而strings是输入的指针数据,当然就改变啦。
[解决办法]
其区别就在于
*(*string++)
与
*(*string)++
这2者的区别就是你的问题的本质!