Re: String Comparision



On Sun, 29 Apr 2007 10:05:20 -0700, "osmium" <r124c4u102@xxxxxxxxxxx>
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.

I think you missed the ; at the end of the for statement.

To the original poster, this is one reason why many recommend
for ( )
;

Rethink your logic.

}

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;
}



Remove del for email
.



Relevant Pages

  • Re: A taxonomy of types
    ... I am describing how to represent the representation (and, ... if the system follows static typing rules (such as in a compiler), ... so, the hardware sees pointers and pointer arithmetic, but the compiler ... "Besides the char types, up to three sizes of integer, declared short int, ...
    (comp.lang.misc)
  • Re: Malloc code
    ... int xxx; ... As for not using the void pointer, I will have to do some further testing ... I just needed some insight on passing arrays of pointers. ... struct MCB *r1; ...
    (microsoft.public.vc.language)
  • I want my segmentation fault!
    ... no occurrences of free and a lot of routines returning pointers to ... the pointer returned by the allocator (either directly or as a component ... int length_of_list; ...
    (comp.lang.c.moderated)
  • Re: Simple question, err... I think
    ... Your nodes contain no other indication of which pointers are valid, ... struct CountedObject ... int is_red; ... bool lament(char const s) ...
    (comp.programming)
  • misc, refocus: new possible lang idea, BSC
    ... object //prototypical object ... it may not be possible to assign between tagged-references and pointers, ... the other, if implemented, will be based on a class/instance system. ... int foo ...
    (comp.lang.misc)