Re: String Comparision



user34 wrote:

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?

....Code snipped....

Thank you all for your help.I have tried to modify the code and here it is .This does show me the correct output but are there any bugs still lurking around which can cause it to fail?

#include <stdio.h>

int comp(const char *s,const char *t)
{
for( ; *s==*t ; s++,t++)
{
if(*s=='\0' || *t=='\0')
break;
}
if(*s=='\0')
return 0;
else
return 1;
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str2))
printf("strings are different");
else
printf("strings are same");
return 0;
}
.



Relevant Pages

  • Re: socket communication: send & receive doesnt work right
    ... But can I actually send and receive strings? ... I did a test of sending two doubles: ... public void send_doubles(double vals, int len) throws ... char *result; ...
    (microsoft.public.win32.programmer.networks)
  • Re: Queue question wih dyn mem alloc
    ... I wrote two functions to pusha character array onto an array and ... int Len=0; ... int push(char **list, char *str, int curlen){ ... arrays to carry an array of strings. ...
    (comp.lang.c)
  • Re: [PATCH] markers: modpost
    ... by merging the name and format strings. ... as long as the marker structs are always defined by this macro. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: [PATCH] markers: modpost
    ... by merging the name and format strings. ... as long as the marker structs are always defined by this macro. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: Can u tell me the explanation reg this problem
    ... main(int argc, char *argv) ... It fails to return an `int' value from the main ... and the first argc elements of the argv ... array point to the strings' initial characters. ...
    (comp.lang.c)