首页 > 解决方案 > 为什么这个 c 程序没有返回我所期望的?

问题描述

我在 c 编程语言方面有点新,我正在努力学习“C 编程语言”一书 - Kerninghan,Ritche。对于练习 2-5 已经做到了这一点,但我不明白为什么 returin 什么都没有......在此先感谢您的帮助。

/*Write a function any() whitch returns the first location in the string s1 where any character from the string s2 occurs,
or -1 if s1 contains no character form s2*/

#include <stdio.h>

int any(char[], char[]);

int main(){
    char str1[] = "string";
    char str2[] = "Monster";

    any(str1, str2);
}

int any(char s1[], char s2[]){
    int i, j;
    int no_match = -1;
        /*Comparing the strings*/
    for(i = 0; s1[i] = '\0'; i++){
        for(j = 0; s2[j] = '\0'; j++)
            if(s2[j] == s1[i])
                return i;
            else if(s2[j] != s1[i])
                    return no_match;
    }
}

标签: c

解决方案


无论any()返回什么都将在该行中被忽略:

any(str1, str2);

如果您需要在控制台上打印它,请使用printf()

printf("%d",any(str1, str2));

此外,s1[i] = '\0'没有任何意义。您想处理直到\0遇到 a ,所以s1[i] != '\0'改为这样做。内循环也一样。


推荐阅读