Re: String Comparision
- From: Martin Ambuhl <mambuhl@xxxxxxxxxxxxx>
- Date: Sun, 29 Apr 2007 14:39:54 -0400
osmium wrote:
"user34" writes:
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);
You return after examining the first char, no matter how it turns out. Rethink your logic.
Not true. He returns after the first instance of *s != *t.
This might not occur within the bounds of the arrays, leading to
attempting addressing errors.
This loop does one of two things
a) crashes with a memory violation or
b) always changes s and t so *s != *t.
His logic is wrong, but so is yours,
He needs to test for at least one of the pointers being 0 in the loop
for( ;*s == *t && *s ; s++, t++) /* empty loop */;
will end when *s is zero (explicit) or when *t is zero and *s isn't (since *s != *t).
Now he can remove the useless
if(*s=='\0')
return 0;
And he should change the subtraction, if only for pedagogical reasons,
Learning to return such a difference is dangerous, since it builds a bad habit that will bite him if
a) the objects compared are not arithmetic or
b) the subtraction might cause an overflow.
In this case, where equality is the only concern, he could simply
return *s != *t;
If he wants to maintain an order, as needed for a comparison function for qsort, the efficiency loss, if it exists at all, is tiny from
return (*s < *t) ? -1 : (*s == *t) ? 0 : 1;
.
}
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;
}
- References:
- String Comparision
- From: user34
- String Comparision
- Prev by Date: Re: String Comparision
- Next by Date: Re: gets() is dead
- Previous by thread: Re: String Comparision
- Next by thread: Re: String Comparision
- Index(es):
Relevant Pages
|