the function can't return int value
int sum_s1=0, sum_s2=0;
int comps(char s1[], char s2[]) {
if (s1[0] == '\0' && s2[0] == '\0') {
if (sum_s1 == sum_s2) {
printf("hihi"); //printable
return 1; //return the 4202692
} else {
return 0;
}
} else {
if (*s1 != '\0') {
if (s1[0]!=32) {
sum_s1 += s1[0];
} else {
sum_s1 += 0;
}
*s1 = *(s1+1);
}
if (*s2 != '\0') {
if (s2[0]!=32) {
sum_s2 += s2[0];
} else {
sum_s2 += 0;
}
*s2 = *(s2+1);
}
if (*s1 != '\0' && *s2 == '\0') equalIgnoreSpace(s1+1, "\0");
if (*s1 == '\0' && *s2 != '\0') equalIgnoreSpace("\0", s2+1);
if (*s1 != '\0' && *s2 != '\0') equalIgnoreSpace(s1+1, s2+1);
if (*s1 == '\0' && *s2 == '\0') equalIgnoreSpace("\0", "\开发者_Go百科0");
}
}
int main() {
int compa=1;
compa = comps("abc f", "abcf");
printf("%d", compa); //return the 4202692
if (compa == 1) {
printf("Two string are equal");
} else {
printf("Two string are not equal");
}
getchar();
return 0;
}
comps()
should return 1
and stop, but I can't get 1 in main function. How can I fix this?
there is no return statement in the comps function [in else case]
int comps(char s1[], char s2[])
{
if (s1[0] == '\0' && s2[0] == '\0')
{
if (sum_s1 == sum_s2)
{
printf("hihi"); //printable
return 1; //return the 4202692
}
else
return 0;
}
else
{
...
...
return code;
}
}
You're trying to modify a static string with *s1 = *(s1+1);
and your program crashes. Try with this instead:
int main() {
int compa=1;
/* Allocated memory can be modified without adverse effects! */
char s1[64];
char s2[64];
strcpy(s1, "abc f");
strcpy(s2, "abcf");
compa = comps(s1, s2);
printf("%d", compa); //return the 4202692
if (compa == 1) {
printf("Two string are equal");
} else {
printf("Two string are not equal");
}
getchar();
return 0;
}
Also, as mentioned by Sourav, comps
is missing return statements. Compiling it gives:
1>c:\code\test\test.cpp(83): warning C4715: 'comps' : not all control paths return a value
And compa
will have an undefined value assigned to it once you assign it the (undefined) return value of comps
.
精彩评论