Re: String Comparision



On Apr 29, 9:53 pm, user34 <use...@xxxxxxxxxxx> wrote:
(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;



}- Hide quoted text -

- Show quoted text -

HI
I tried this code, it works fine!!, no idea what error u are getting..
and even the concept seems to be ok
Aditya

.



Relevant Pages

  • Re: String Comparision
    ... code which would compare two strings using pointers. ... 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. ... He needs to test for at least one of the pointers being 0 in the loop ... And he should change the subtraction, if only for pedagogical reasons, ...
    (comp.lang.c)
  • Re: Array comparison
    ... pointers are only going to compare their object pointers ... pointers and not the contents of the strings. ... things like array of Char, bytes, words, dword, int64's etc.. ...
    (alt.comp.lang.borland-delphi)
  • Re: comparing ptrs/mmap
    ... I have two pointers, the first of which is mmapped ... int compare1 ... there may be some other guarantees of the ability to compare pointers ... int compare2(const void *a, const void *b) ...
    (comp.lang.c)
  • Re: AutoPtr::operator == : Is it defined the correct way ??
    ... nothing but wrappers around char* pointers)? ... Do we compare the internal ... Well, no. Strings are strings, pointers are pointers, value types are value ... Let's say you cannot afford the luxury to use CAutoPtr and have to use good ...
    (microsoft.public.vc.atl)
  • Re: comparing ptrs/mmap
    ... I have two pointers, the first of which is mmapped ... int compare1 ... is there a way to write compare1that is safe? ... when is it safe to compare pointers? ...
    (comp.lang.c)