Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: do I need strcmp ? |
| Date | 2011-11-04 22:16 +0000 |
| Organization | PANIX Public Access Internet and UNIX, NYC |
| Message-ID | <j91o8r$av8$1@reader1.panix.com> (permalink) |
| References | <4eb4605c$0$20319$bbae4d71@news.suddenlink.net> |
In <4eb4605c$0$20319$bbae4d71@news.suddenlink.net> "Bill Cunningham" <nospam@nspam.invalid> 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
gordon@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
do I need strcmp ? "Bill Cunningham" <nospam@nspam.invalid> - 2011-11-04 17:59 -0500
Re: do I need strcmp ? John Gordon <gordon@panix.com> - 2011-11-04 22:16 +0000
Re: do I need strcmp ? "Bill Cunningham" <nospam@nspam.invalid> - 2011-11-04 18:20 -0500
Re: do I need strcmp ? Martin Ambuhl <mambuhl@earthlink.net> - 2011-11-04 18:36 -0400
Re: do I need strcmp ? Nick Keighley <nick_keighley_nospam@hotmail.com> - 2011-11-06 15:05 -0800
Re: do I need strcmp ? Keith Thompson <kst-u@mib.org> - 2011-11-06 15:25 -0800
csiph-web