该函数不能返回int值

时间:2011-04-23 05:38:37

标签: c

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", "\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()return 1并停止,但我无法在主要功能中获得1。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

comps函数[in else case]

中没有return语句
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;
 }   
}

答案 1 :(得分:0)

您尝试使用*s1 = *(s1+1); 修改静态字符串,并且程序崩溃。请尝试使用此功能:

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

此外,如Sourav所述,comps缺少返回语句。编译它给出:

1>c:\code\test\test.cpp(83): warning C4715: 'comps' : not all control paths return a value

一旦为compa分配(未定义的)返回值,comps将为其分配一个未定义的值。