Re: String Comparision
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sun, 29 Apr 2007 13:30:09 -0700
user34 <user34@xxxxxxxxxxx> writes:
(Sorry if this gets posted twice)
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?
#include<stdio.h>
int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
}
int main(void)
{
char str[]="Hello";
char str2[]="Hello";
if(comp(str,str2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
More whitespace would be very helpful (not to the compiler, but to
your readers).
Your logic error is that, if s and t point to identical strings, you
don't stop scanning when you reach the end.
You say that the strings are modified, but the code you posted doesn't
attempt to demonstrate that. Looking at the code, it does modify the
values of s and t (as it's designed to do). But s and t are pointers,
not strings. The strings themselves are not modified.
Remember that a "string" is "a contiguous sequence of characters
terminated by and including the first null character" (C99 7.1.1p1).
It's a data layout, not a data type.
For example:
char str[] = "Hello";
char *s;
s = str;
/*
* s points to the string "Hello". (It actually points
* to the first character of the string; we refer to
* a pointer to the first character of a string as a
* pointer to the string itself).
*/
s++;
/*
* Now s points to the string "ello" (which is the trailing
* portion of the string "Hello"). The original string
* "Hello" is still there in all its salutational glory,
* and we haven't modified that string. We've merely
* modified the pointer s so it points to a different
* string, one that happens to be part of the original
* string.
*/
If you haven't already done so, take a look at the comp.lang.c FAQ,
<http://www.c-faq.com/>. Sections 4 (Pointers), 6 (Arrays and
Pointers) and 8 (Characters and Strings) should be particularly
relevant to your current issues.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- References:
- String Comparision
- From: user34
- String Comparision
- Prev by Date: Re: gets() is dead
- Next by Date: Re: gets() is dead
- Previous by thread: Re: String Comparision
- Next by thread: Re: String Comparision
- Index(es):
Relevant Pages
|