![](templates/subSilver/images/CCSLogo.jpg) |
![CCS C Software and Maintenance Offers](templates/subSilver/images/forumAd6.jpg) |
View previous topic :: View next topic |
Author |
Message |
Fabri
Joined: 22 Aug 2005 Posts: 275
|
problem in use of STRCMP() |
Posted: Sat Dec 10, 2005 5:05 am |
|
|
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, |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah Guest
|
|
Posted: Sat Dec 10, 2005 9:31 am |
|
|
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 |
|
![](templates/subSilver/images/spacer.gif) |
|
|
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
|