In <4eb4605c$0$20319$> "Bill Cunningham" <> writes:
> I am doing a comparison here and the code works and then doesn't work.
> My goal is to start a string to be recognized by a function only if it
> starts with a +. Kind of like cpp doesn't recognize preprocessor commands
> unless # is present.
> #include <stdio.h>
> #include <string.h>
> int main()
> {
> char *plus;
> char *string = "+ hello there\n";
> plus = strchr(string, '+');
> if ((int) plus[0] == '+')
> printf("ok\n");
> if ((int) plus[0] != '+')
> printf("no\n");
> }
> This code as it is works marvelously when finding + in a string. If
> something other than + is used, I do not get no but a segmentation fault. Is
That's because strchr returns NULL when the target character is not found,
which causes 'plus' to have a null value. Then, when you attempt to
look at plus[0], the program crashes.
> the only way around this to use strcmp to see if the first character of the
> string is + or not? Can the code be changed to accomplish what I want
> without using strcmp?
Using strchr seems like overkill in this case. You don't even need the
'plus' variable. Just look for the character directly:
char *string = "+hello there\n";
if(string[0] == '+')
printf("ok\n");
else
printf("no\n");
--
John Gordon A is for Amy, who fell down the stairs
B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"