【发布时间】:2017-08-02 05:23:41
【问题描述】:
我正在尝试测试“C 上的指针”中的一些代码,find_char 函数用于搜索指定的字符。我添加了自己的一些东西,即调用 find_char 并包含要搜索的初始化数据(指向 char 的指针数组)的 main() 函数。我设法在编译时修复了所有错误和警告,但是在尝试运行 a.out 文件时,我得到了分段错误错误。
我知道分段错误主要与数组和指针有关,当类型转换不正确时经常发生这种情况。但是我真的找不到我的代码有什么问题。
非常感谢。
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int find_char( char **strings, char value);
int main(void)
{
int i;
char c = 'z';
char *pps[] = {
"hello there",
"good morning",
"how are you"
};
i = find_char(pps, c);
printf("%d\n", i);
return 0;
}
int find_char (char **strings, char value)
{
char *string;
while (( string = *strings++) != NULL)
{
while (*string != '\0')
{
if( *string++ == value )
return TRUE;
}
}
return FALSE;
}
【问题讨论】:
-
如果您要在字符串指针数组中测试空字符串指针,也许您实际上应该在列表末尾放置一个。 IE。
"how are you", NULL。现在你的代码碰到了最后一个字符串(这显然是非空的),然后继续前进到以太中寻找你要求它的确切内容:NULL。 -
或者将字符串的数量作为参数传递给
find_char,例如int find_char( char **strings, size_t n, char value);并使用for (size_t i = 0; i < n; i++)循环或while (n--)进行迭代以仅迭代正确数量的指针。