-
string sort madness
OK, so I've got these two functions for sorting a dictionary:
Code:
void dicsort(int diclength, char dic[][stringlength]) {
int i, j;
char temp[stringlength];
for (i = 0; i < diclength; ++i)
for (j = 0; j < diclength - 1; ++j) {
if (strcomp(dic[j],dic[j+1]) > 0) {
strcopy(dic[j],temp);
strcopy(dic[j+1],dic[j]);
strcopy(temp,dic[j]);
}
}
}
//-1 if str1 < str2, 0 if str1 == str2, 1 if str1 > str2
int strcomp(char* str1, char* str2) {
if (strequal(str1,str2))
return 0;
int i;
for (i = 0; i <= strlength(str1); ++i) {
if (i > strlength(str2))
return 1;
if (str1[i] < str2[i])
return -1;
if (str1[i] > str2[i])
return 1;
}
return 0;
}
but when I run them, it seems I'm sending the same two strings to strcomp() every time. This is baffling me, and I can't use any <cstring> goodness. I know that there aren't any duplicates in dic, and I know all my other strwhatever()'s work fine. Does anybody have any idea why this is happening?
-
Look what's happening here:
>> strcopy(dic[j],temp);
>> strcopy(dic[j+1],dic[j]);
>> strcopy(temp,dic[j]);
You are using 'dic[j]' to preserve 'temp' - is that what you wanted to do?
One more thing:
>> for (i = 0; i <= strlength(str1); ++i)
>> if (i > strlength(str2))
Each iteration of the loop you are calling 'strlength()' on 'str1' and 'str2'. You only need to calculate these lengths once.
-
The strcopy function I made's prototype looks like:
Code:
void strcopy(char* from, char* to);
, so the calls I have should be swapping str1 and str2 should work ok. Is there some standard function that I could be having a conflict with? I'm still stumped.