簡體   English   中英

該函數無法返回int值

[英]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", "\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並停止,但是我不能在main函數中得到1。 我怎樣才能解決這個問題?

comps函數中沒有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;
 }   
}

您正在嘗試使用*s1 = *(s1+1);修改靜態字符串*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缺少return語句。 編譯可以得到:

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

一旦為compa分配了comps的(未定義)返回值,就會為它分配一個未定義的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM