CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

problem in use of STRCMP()

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Fabri



Joined: 22 Aug 2005
Posts: 275

View user's profile Send private message

problem in use of STRCMP()
PostPosted: Sat Dec 10, 2005 5:05 am     Reply with quote

Hi Everybody,

I don't understand why STRCMP() doesn't return 0 when two string are identical.
I have:
Quote:

char string1[2];
char string2[2];
int8 res;

strcpy(string1,"PO");
strcpy(string2,"PO");

res=strcmp(string1,string2);


The routine return res=1;

Is this correct way to compare two string ?

If I have:


Quote:

res=strcmp(string1,string1);


The return value of res is 0.

my compiler version is PCWH 3.235 with PIC18F2455.

Thanks to support,
Ttelmah
Guest







PostPosted: Sat Dec 10, 2005 9:31 am     Reply with quote

The problem is that your strings are too long, and one at least is getting corrupted.
Basically the string "PO", requires _three_ characters to store. The two characters for the text itself, and one character for the 0 'terminator' character. What happens, is that the two strings you declare are sitting in memory one after the other,so there is a block of memory after the copies, that looks like this:
Code:


location for string1     'P'
                                'O'
location for string2     'P'
                                'O'
location for res          '\000'


The first strcpy, copies "PO\000" into the three locations starting at the location for string1. Then the second copies the same values into the location starting where 'string2' is stored, and overwriting the 'res' value, with a zero.
Then when you do the comparison, you actually compare "PO\000", with "POPO\000", which returns a 'no match' condition into 'res'. If however you compare string1, with itself, there is a match (the same would also be true if you compared string2 with itself).
So, the simple answer is, to ensure you allocate enough space for the strings. If you increase the declarations to three characters, the code will work.
You must _allways_ be very careful in C, to remember this extra character.

Best Wishes
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group