I am trying to test some code from "Pointers On C", the find_char function, which searches for a specified character. I added something of my own, that is, the main() function that calls the find_char and includes the initialized data to be searched(an array of pointers to char). I managed to fix all errors and warnings at compile time, but while trying to run the a.out file, I got the segmentation fault error.
I know segmentation fault is mostly concerned with array and pointers which so often happens when types are incorrectly translated. But I really can't find what is wrong with my code.
Thank you so much.
#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;
}
"how are you", NULL. Right now your code hits the last string (which is obviously non-null), then just continues marching into the ether in search of exactly what you asked it to: a NULL.find_char, e.g.int find_char( char **strings, size_t n, char value);and iterate with afor (size_t i = 0; i < n; i++)loop orwhile (n--)to only iterate over the proper number of pointers.