您的位置:首页 > 其它

用指针传递函数参数的问题

2010-03-26 19:18 288 查看
下面的find_char是一个在一组字符串中查找某一字符的程序。
 
 
 
 
#include <stdio.h>

#define TRUE 1
#define FALSE 0
#define LENGTH 10

int find_char( char **strings, int value)
{
//对于列表中的每个字符串
while( *strings != NULL)
{

//观察字符串中的每个字符,看看它是否是我们查找的那个
while( **strings != '/0')
{
if( *(*strings)++ == value )
return TRUE;
}
strings++;//改变了strings指针指向的位置,strings指针最后会等于NULL
}
return FALSE;
}

void main()
{
char* str[LENGTH] = {"hello", "world", NULL};
char ch = 'd';

printf("The original string is /"%s %s/"/n", str[0], str[1]);

if( find_char(str, ch) == TRUE )
{
printf("%c was found!/n", ch);
}
else
{
printf("%c was not found!/n", ch);
}

printf("The string now is /"%s %s/"/n", str[0], str[1]);
}

运行这个版本的find_char后会使原字符串数组str指向NULL指针。而下面这个版本的find_char却不会。
 
 
 
 
 
 
int find_char( char **strings, char value)
{
char *string;	//我们当前正在查找的字符串

//对于列表中的每个字符串
while( (string = *strings++) != NULL)
{

//观察字符串中的每个字符,看看它是否是我们查找的那个
while( *string != '/0')
{
if( *string++ == value )
return TRUE;
}

}
return FALSE;
}

这是为什么呢?strings是参数的一个拷贝,它传递了一个地址,第一个程序中的if( *(*strings)++ == value )通过(*strings)++改变了地址里的内容,影响了原变量;而第二个程序里的while( (string = *strings++) != NULL)只改变了拷贝strings的值,却没有改变地址里的内容(*strings)的值,不影响原变量。
 
 
两个find_char函数的出处:
《C和指针》。Kenneth A. Reek 著,徐波译。人民邮电出版社。第106~107页。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string null 出版 c