473,386 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

String Comparision

(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;
}
Apr 29 '07 #1
35 2840
"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.
}

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

Apr 29 '07 #2
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.
Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
Apr 29 '07 #3
user34 wrote, On 29/04/07 17:53:
(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?
First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.
#include<stdio.h>
They stopped charging for white space yesterday, so your could make the
above easier to read by doing
#include <stdio.h>
int comp(char *s,char *t)
Since this function is not meant to modify the strings it would be
better to make it explicit
int comp(const char *s,const char *t)

This will also mean the compiler will bitch at you if you try to modify
them.
{
for(;*s==*t;s++,t++);
It is easy to fail to spot the semicolon above, for the human reader
something like
for (; *s==*t; s++,t++) continue;
Or
for (; *s==*t; s++,t++) /* do nothing */ ;
Or
for (; *s==*t; s++,t++) {}

Also, what if both strings are entirely the same? In that case you will
not stop at the end of the strings but will continue going in to the
wild blue yonder.
for (; *s && *s==*t; s++,t++) continue;
if(*s=='\0')
return 0;
else
return (*s -*t);
You do not need the parenthesis
return *s - *t;

Also, on some embedded systems where a byte (in C terms) is 16 bits or
larger and the same size as an int this could fail.
return (*s *t) ? 1 : -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;
}
You should add a newline on to the end of the strings. One easy way as
you are not using any format specifiers is to call puts instead of printf.
--
Flash Gordon
Apr 29 '07 #4
user34 wrote, On 29/04/07 18:15:
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.

Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
Also it won't stop at the end of the strings if they are the same.
--
Flash Gordon
Apr 29 '07 #5
jg
On Apr 29, 9:53 am, user34 <use...@invalid.comwrote:
for(;*s==*t;s++,t++);
Need to check both s and t are not pointing to somewhere
out of the string.
JG

Apr 29 '07 #6
Flash Gordon wrote:
user34 wrote, On 29/04/07 17:53:
>(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?

First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.
I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same 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;
}
Apr 29 '07 #7
user34 wrote, On 29/04/07 18:29:
Flash Gordon wrote:
>user34 wrote, On 29/04/07 17:53:
>>(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?

First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.

I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!
<snip>

Then your description of the problem is inaccurate, the code does not
modify the strings. I suggest you examine the improvements and comments
by myself and the others and see if it then works.
--
Flash Gordon
Apr 29 '07 #8
"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);
}

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;
}
The first problem I note is that the terminating condition on the for loop
should be an '\0', signifying end of string. This suggests the middle
expression should be something like

*s!='\0' && *t'='\0'

But this doesn't work because we don't know if both strings are the same
length. So now we precede your code with something to find the length of
the strings. But that uses stuff in <string.h>, the very thing you are
trying to avoid! But then note that you are barely using a for loop, it is
a force fit. I suggest you rewrite using a while loop. I don't like
suggesting new and different ways to attack a problem, but even more, I
don't like the code I foresee if the for loop approach is continued.

I consider the primary good attribute of a for loop the index variable. But
you don't *use* an index variable.

Apr 29 '07 #9
osmium wrote, On 29/04/07 19:03:
"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);
}

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

The first problem I note is that the terminating condition on the for loop
should be an '\0', signifying end of string. This suggests the middle
expression should be something like

*s!='\0' && *t'='\0'

But this doesn't work because we don't know if both strings are the same
length. So now we precede your code with something to find the length of
the strings.
Actually, you don't have to worry about whether the strings are the same
length, of even check for the end of both strings. After all, is the
strings are of different lengths then when you get to the end of the
shorter string you will find that '\0'!=character.
But that uses stuff in <string.h>, the very thing you are
trying to avoid! But then note that you are barely using a for loop, it is
a force fit. I suggest you rewrite using a while loop. I don't like
suggesting new and different ways to attack a problem, but even more, I
don't like the code I foresee if the for loop approach is continued.

I consider the primary good attribute of a for loop the index variable. But
you don't *use* an index variable.
The approach used by the OP is not bad, it just has an error in it.
Using an index variable is also perfectly acceptable IMHO since a decent
optimising compiler will happily convert from one to the other depending
on what is more efficient for the processor.
--
Flash Gordon
Apr 29 '07 #10
"user34" wrote:
osmium wrote:
>You return after examining the first char, no matter how it turns out.
Rethink your logic.

Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
If you really prefer a for loop based solution, I would do it something like
this. As far as I know it works.
--------------------------
#include <stdio.h>

// return 1 iff they are equal (inverted sense from what you had)
int comp(char a[], char b[])
{
for(int i=0; ; i++)
{
if(a[i] != b[i])
return 0;
/* assert: a[i] == b[i], we just tested it
but it it the end of the string? */
if(a[i] == '\0')
return 1;
}
}
/*=============*/
int main()
{
char s[] = "test";
char t[] = "test";
if(comp(s, t))
printf("Same\n");
else
printf("Different");
return 0;
}
Apr 29 '07 #11
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;
}

Apr 29 '07 #12
user34 <us****@invalid.comwrites:
(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) ks***@mib.org <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"
Apr 29 '07 #13
On Sun, 29 Apr 2007 10:05:20 -0700, "osmium" <r1********@comcast.net>
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
Apr 29 '07 #14
user34 wrote:

I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!

#include<stdio.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.


Brian
Apr 29 '07 #15
On Apr 30, 5:46 am, Flash Gordon <s...@flash-gordon.me.ukwrote:
Then your description of the problem is inaccurate, the code does not
modify the strings. I suggest you examine the improvements and comments
by myself and the others and see if it then works.
He never said it did. He said that "s" and "t" were modified.
Those are pointers to char, which he increments in each
loop iteration.
Apr 29 '07 #16
Old Wolf wrote, On 29/04/07 23:40:
On Apr 30, 5:46 am, Flash Gordon <s...@flash-gordon.me.ukwrote:
>Then your description of the problem is inaccurate, the code does not
modify the strings. I suggest you examine the improvements and comments
by myself and the others and see if it then works.

He never said it did. He said that "s" and "t" were modified.
Those are pointers to char, which he increments in each
loop iteration.
I can't remember exactly what he said, but my mental filters would
probably have assumed that as he was explicitly modifying those
variables he would not be surprised by them changing value. Of course, I
could be wrong.
--
Flash Gordon
Apr 29 '07 #17
Default User wrote:
user34 wrote:

I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!

#include<stdio.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.
Or maybe it did. Either way, it's not going to work.

If you leave the semicolon in, then if the strings are identical then
you read off the end of each into memory that might not belong to the
strings, or memory that had never been initialized. At any rate, it
will report a false mismatch, because it will continue that until
there's a difference.

Brian
Apr 29 '07 #18
Barry Schwarz wrote:
>
.... snip ...
>
I think you missed the ; at the end of the for statement.

To the original poster, this is one reason why many recommend
for ( )
;
I use "for (whatever) continue;".

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Apr 30 '07 #19
On Apr 29, 9:53 pm, user34 <use...@invalid.comwrote:
(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

Apr 30 '07 #20
On 29 Apr 2007 15:40:26 -0700, Old Wolf <ol*****@inspire.net.nz>
wrote:
>On Apr 30, 5:46 am, Flash Gordon <s...@flash-gordon.me.ukwrote:
>Then your description of the problem is inaccurate, the code does not
modify the strings. I suggest you examine the improvements and comments
by myself and the others and see if it then works.

He never said it did. He said that "s" and "t" were modified.
Those are pointers to char, which he increments in each
loop iteration.
Yes he did. From the original message that started this thread

"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."

Notice "...the strings ... get modified...." In any event, it
probably means he was misinterpreting the output from his debugger.
When pointers s and t get modified (which we all agree is the actual
modification that occurs) to point past the terminating '\0'
characters, his debugger probably attempted to show him the "string"
at the new address. Since he was in the realm of undefined behavior
at this point, what the debugger showed was equally undefined and no
longer relevant to his question.
Remove del for email
Apr 30 '07 #21
On 30 Apr 2007 00:58:55 -0700, Aditya <ad************@gmail.com>
wrote:
snip code which has been analyzed to death with the two major errors
identified repeatedly.
>HI
I tried this code, it works fine!!, no idea what error u are getting..
and even the concept seems to be ok
Aditya
How many times is the for loop in function comp executed? Is it more
than 6 (the number of characters in each string being compared)? What
are the values of s and t (or what do they point to) on the 7th
iteration of the loop (hint: on the sixth iteration each points to a
'\0')? Do you know what the technical term for this condition is
called (hint: look up undefined behavior)?
Remove del for email
Apr 30 '07 #22

"Default User" <de***********@yahoo.comwrote in message
news:59*************@mid.individual.net...
user34 wrote:

>I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!

#include<stdio.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.
What semicolon? That is a comma.
--
Fred L. Kleinschmidt
Apr 30 '07 #23
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;
}
Apr 30 '07 #24
Fred Kleinschmidt said:
>
"Default User" <de***********@yahoo.comwrote in message
news:59*************@mid.individual.net...
>user34 wrote:

>>I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!

#include<stdio.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.

What semicolon? That is a comma.
From here, it's whitespace. But in Default User's original reply, it was
a 't'.

Methinks Brian composes news articles using a proportional font.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 30 '07 #25
Fred Kleinschmidt wrote:
>
"Default User" <de***********@yahoo.comwrote in message
news:59*************@mid.individual.net...
user34 wrote:

I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!
>
#include<stdio.h>
>
int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.

What semicolon? That is a comma.

You should use a non-proportional font for usenet. I could guess
(correctly) that you use Outlook Express.


Brian

Apr 30 '07 #26
Richard Heathfield wrote:
Fred Kleinschmidt said:

"Default User" <de***********@yahoo.comwrote in message
news:59*************@mid.individual.net...
user34 wrote:
>
>
I did not retype the code !
Here it is once again (without any of the above suggested
improvements)and it still shows me the same error!

#include<stdio.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++,t++);
^
That semicolon doesn't belong.
>
What semicolon? That is a comma.

From here, it's whitespace. But in Default User's original reply, it
was a 't'.

Methinks Brian composes news articles using a proportional font.
No, I use a non-proportional font. My newsreader uses Courier New. My
reply to my original message did bump it over into whitespace, but that
seems to be an artifact of the quoting mechanism.

Brian

Apr 30 '07 #27

"user34" <us****@invalid.comwrote in message news:f1**********@aioe.org...
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;
}

What happens if string s is a proper prefix of string t?

--
Jonas
Apr 30 '07 #28
user34 wrote:
>
.... snip ...
>
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;
}
Try this:

int comp(const char *s, const char *t) {

while (*s && (*s == *t) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */

and think about what my code actually does.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

May 1 '07 #29
Jonas wrote:
"user34" <us****@invalid.comwrote in message news:f1**********@aioe.org...
>user34 wrote:
What happens if string s is a proper prefix of string t?
yes i did find it out while testing the code and realised my error
This is the modified code.I believe my logic is correct here though at
the expense of some extra numbers of checks.

#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' && *t=='\0')
return 0;
else
return 1;
}

int main(void)
{
char str[]="The C programming Language";
char str2[]="The C programming Language ";

if(comp(str,str2))
printf("Strings are different\n");
else
printf("Strings are same\n");
return 0;
}

May 1 '07 #30
On Mon, 30 Apr 2007 21:11:55 -0400, CBFalconer <cb********@yahoo.com>
wrote:
>user34 wrote:
>>
... snip ...
>>
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;
}

Try this:

int comp(const char *s, const char *t) {

while (*s && (*s == *t) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I tried it, but got the following compiler error:

error C2146: syntax error : missing ')' before identifier 's'

After fixing that error, and running my program, this call:

comp("Hello", NULL);

produces an error message box on my OS that states the following:

"A problem caused the program to stop working correctly. Windows will
close the program and notify you if a solution is available."

We should all strive to make sure that any code we submit to this
newsgroup at least compiles with no errors (and preferably with no
warnings, to the best of our ability), and that simple test cases on
our code do not result in undefined behavior.

I'm posting this under Windows Vista after compiling my code with VC++
6.0 SP5, but I could *almost* just as easily posted this under Ubuntu
Linux 6.10 after compiling my code with "gcc -Wall -W -ansi -pedantic
-o c.exe c.c" (after unplugging my Microchip PICDEM 2 Plus ICD USB
device and ACS ACR38 USB smart card reader, of course, because Ubuntu
Linux 6.10 hangs on boot if I have either of these devices plugged in,
for whatever reason).

Best regards
--
jay
http://www.linux-mag.com/id/2940/
http://news.zdnet.co.uk/software/0,1...9286295,00.htm
http://www.microsoft.com/windows/products/windowsvista/
May 1 '07 #31
jaysome wrote:
CBFalconer <cb********@yahoo.comwrote:
.... snip ...
>>
Try this:

int comp(const char *s, const char *t) {

while (*s && (*s == *t) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */

I tried it, but got the following compiler error:

error C2146: syntax error : missing ')' before identifier 's'

After fixing that error, and running my program, this call:

comp("Hello", NULL);

produces an error message box on my OS that states the following:

"A problem caused the program to stop working correctly. Windows will
close the program and notify you if a solution is available."

We should all strive to make sure that any code we submit to this
newsgroup at least compiles with no errors (and preferably with no
warnings, to the best of our ability), and that simple test cases on
our code do not result in undefined behavior.

I'm posting this under Windows Vista after compiling my code with VC++
6.0 SP5, but I could *almost* just as easily posted this under Ubuntu
Linux 6.10 after compiling my code with "gcc -Wall -W -ansi -pedantic
-o c.exe c.c" (after unplugging my Microchip PICDEM 2 Plus ICD USB
device and ACS ACR38 USB smart card reader, of course, because Ubuntu
Linux 6.10 hangs on boot if I have either of these devices plugged in,
for whatever reason).
If you want to pass NULL to a routine that expects a string, you
need to test for it. So you could use:

int comp(const restrict char *s, const char *t) {

if (!s && !t) return 1; /* assuming boh NULL is equal */
else if (!s || !t) return 0;
while (*s && (*s == *t)) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

May 1 '07 #32
CBFalconer wrote:
jaysome wrote:
>CBFalconer <cb********@yahoo.comwrote:
... snip ...
>>Try this:

int comp(const char *s, const char *t) {

while (*s && (*s == *t) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I tried it, but got the following compiler error:

error C2146: syntax error : missing ')' before identifier 's'

After fixing that error, and running my program, this call:

comp("Hello", NULL);

produces an error message box on my OS that states the following:

"A problem caused the program to stop working correctly. Windows will
close the program and notify you if a solution is available."

We should all strive to make sure that any code we submit to this
newsgroup at least compiles with no errors (and preferably with no
warnings, to the best of our ability), and that simple test cases on
our code do not result in undefined behavior.

I'm posting this under Windows Vista after compiling my code with VC++
6.0 SP5, but I could *almost* just as easily posted this under Ubuntu
Linux 6.10 after compiling my code with "gcc -Wall -W -ansi -pedantic
-o c.exe c.c" (after unplugging my Microchip PICDEM 2 Plus ICD USB
device and ACS ACR38 USB smart card reader, of course, because Ubuntu
Linux 6.10 hangs on boot if I have either of these devices plugged in,
for whatever reason).

If you want to pass NULL to a routine that expects a string, you
need to test for it. So you could use:

int comp(const restrict char *s, const char *t) {

if (!s && !t) return 1; /* assuming boh NULL is equal */
else if (!s || !t) return 0;
while (*s && (*s == *t)) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I'm not convinced that simple library functions should do anything
special when confronted with bad input. Our 'int comp(char *s, char *t)'
will yield a zero if equal, negative if less-than, otherwise greater.
There doesn't seem to be any room in the three-piece return domain for
an error code.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
May 2 '07 #33
Joe Wright wrote, On 02/05/07 01:22:
CBFalconer wrote:
>jaysome wrote:
>>CBFalconer <cb********@yahoo.comwrote:
... snip ...
>>>Try this:

int comp(const char *s, const char *t) {

while (*s && (*s == *t) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I tried it, but got the following compiler error:

error C2146: syntax error : missing ')' before identifier 's'

After fixing that error, and running my program, this call:

comp("Hello", NULL);

produces an error message box on my OS that states the following:

"A problem caused the program to stop working correctly. Windows will
close the program and notify you if a solution is available."

We should all strive to make sure that any code we submit to this
newsgroup at least compiles with no errors (and preferably with no
warnings, to the best of our ability), and that simple test cases on
our code do not result in undefined behavior.

I'm posting this under Windows Vista after compiling my code with VC++
6.0 SP5, but I could *almost* just as easily posted this under Ubuntu
Linux 6.10 after compiling my code with "gcc -Wall -W -ansi -pedantic
-o c.exe c.c" (after unplugging my Microchip PICDEM 2 Plus ICD USB
device and ACS ACR38 USB smart card reader, of course, because Ubuntu
Linux 6.10 hangs on boot if I have either of these devices plugged in,
for whatever reason).

If you want to pass NULL to a routine that expects a string, you
need to test for it. So you could use:

int comp(const restrict char *s, const char *t) {

if (!s && !t) return 1; /* assuming boh NULL is equal */
else if (!s || !t) return 0;
while (*s && (*s == *t)) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I'm not convinced that simple library functions should do anything
special when confronted with bad input. Our 'int comp(char *s, char *t)'
will yield a zero if equal, negative if less-than, otherwise greater.
There doesn't seem to be any room in the three-piece return domain for
an error code.
It could be argued that a lack of a string (null pointer) is less than
an empty string, and that if both elements are "lack of string" (null
pointers) they are of the same value. So there is a logical (to me)
ordering that can be applied.

Of course, if the input is defined as being strings and not null
pointers then ignoring the problem at that level and ensuring the caller
gets it right is certainly a valid option.
--
Flash Gordon
May 2 '07 #34
Flash Gordon wrote:
Joe Wright wrote, On 02/05/07 01:22:
>CBFalconer wrote:
.... snip ...
>>
>>If you want to pass NULL to a routine that expects a string, you
need to test for it. So you could use:

int comp(const restrict char *s, const char *t) {

if (!s && !t) return 1; /* assuming boh NULL is equal */
else if (!s || !t) return 0;
while (*s && (*s == *t)) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */
I'm not convinced that simple library functions should do
anything special when confronted with bad input. Our 'int
comp(char *s, char *t)' will yield a zero if equal, negative if
less-than, otherwise greater. There doesn't seem to be any room
in the three-piece return domain for an error code.
Then don't test for the NULLs.
>
It could be argued that a lack of a string (null pointer) is less
than an empty string, and that if both elements are "lack of
string" (null pointers) they are of the same value. So there is a
logical (to me) ordering that can be applied.
Which is exactly what the above code does.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

May 2 '07 #35
CBFalconer wrote, On 02/05/07 13:03:
Flash Gordon wrote:
>Joe Wright wrote, On 02/05/07 01:22:
>>CBFalconer wrote:
... snip ...
>>>If you want to pass NULL to a routine that expects a string, you
need to test for it. So you could use:

int comp(const restrict char *s, const char *t) {

if (!s && !t) return 1; /* assuming boh NULL is equal */
else if (!s || !t) return 0;
while (*s && (*s == *t)) s++, t++;
/* now either *s == 0 or *s != *t */
return *s == *t; /* 0 or 1 */
} /* untested */

I'm not convinced that simple library functions should do
anything special when confronted with bad input. Our 'int
comp(char *s, char *t)' will yield a zero if equal, negative if
less-than, otherwise greater. There doesn't seem to be any room
in the three-piece return domain for an error code.

Then don't test for the NULLs.
Which I suggested as valid when the caller will have responsibility for
ensuring that is true.
>It could be argued that a lack of a string (null pointer) is less
than an empty string, and that if both elements are "lack of
string" (null pointers) they are of the same value. So there is a
logical (to me) ordering that can be applied.

Which is exactly what the above code does.
I was commenting on Joe's comment on the code, not directly on the code.
--
Flash Gordon
May 2 '07 #36

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Forecast | last post by:
I run the following code in UNIX compiled by g++ 3.3.2 successfully. : // proj2.cc: returns a dynamic vector and prints out at main~~ : // : #include <iostream> : #include <vector> : : using...
6
by: rakesh | last post by:
Hi, I have a requirement in which I need to search a string in a file stored on a harddisk. String which needs to be searched would be stored in a file with delimiter as new line character. some...
32
by: Wolfgang Draxinger | last post by:
I understand that it is perfectly possible to store UTF-8 strings in a std::string, however doing so can cause some implicaions. E.g. you can't count the amount of characters by length() | size()....
3
by: kd | last post by:
Hi All, How to perform case-insensitive comparision of strings? Would there be some kind of an indicator, which when set to true, would allow case-insenitive comparision of strings using...
2
by: nirav.lulla | last post by:
I have been given the task to come up with Requirements, Comparision and Migration document from Shadow Direct to DB2 Connect. I am very new much to all this, but kind of know a little bit about...
30
by: Steve Edwards | last post by:
Hi, I'm re-writing some code that had relied on some platform/third-party dependent utility functions, as I want to make it more portable. Is there a standard C/C++/stl routine for changing an stl...
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
8
by: abhi147 | last post by:
Hi all , I need to convert a 32 bit string containing hex digits like "76d408cedd600bb578bc0256a751cea2" into it's corresponding 16bit ascii value like "vÎÝ` µx¼V§Q΢" . Now the presence of...
9
by: subramanian100in | last post by:
Suppose we have char *a = "test message" ; Consider the comparison if (a == "string") ..... Here "string" is an array of characters. So shouldn't the compiler
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.