首页 > 解决方案 > 为什么这个程序给变量 j 分配了一个奇怪的数字?

问题描述

我正在与 Kernighan & Ritchie 2nd Ed 一起学习 C。本书,我目前在第 2 章。本章中的第五个练习要求读者“编写函数 any(s1,s2),它返回字符串 s1 中出现字符串 s2 中的任何字符的第一个位置,如果 s1 不包含来自 s2 的字符,则为 -1。”

我做了我的程序,但我也去寻找其他人的答案,看看其他人解决问题的方法。我在这个链接上发现了这个程序。

    #include<stdio.h>
#define MAXLINE 1000

int mgetline(char line[],int maxline);
int any(char s1[],char s2[]);

int main(void)
{
    char s1[MAXLINE],s2[MAXLINE];
    int val;
    
    /* Give the first string s1 */
    
    mgetline(s1,MAXLINE);
    
    /* Give the second string s2 */

    mgetline(s2,MAXLINE);

    val = any(s1,s2);

    printf("%d",val);

    return 0;
}

int mgetline(char s[],int lim)
{
    int i,c;
    for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
        s[i]=c;

    if(c=='\n')
        s[i++]=c;
    s[i]='\0';
}

int any(char s1[],char s2[])
{
    int i, j, check_next_char;

    check_next_char = 1;

    for(i = 0; s1[i] != '\0' && (check_next_char);) 
    {
        // iterate through s2 while trying to find matching character from s1
        for(j = 0; s2[j] != '\0' && (s1[i] != s2[j]); ++j) 
            ; // continue

        if(s2[j] == '\0') {
            check_next_char=1;
            i++; // go for the next char in s1
        }
        else
            check_next_char=0; // match found
    }

    if(s1[i] == '\0')
        return -1;
    else
        return i;
}

问题在于功能any。每当我编写不共享任何字符的字符串时,变量 j 在第一个循环中被赋值为 10,然后随着循环的进行一些随机数。我找不到代码的问题。这种行为的原因可能是什么?

标签: cfor-loopkernighan-and-ritchie

解决方案


新行字符 '\n' 也被视为要比较的字符。根据您的程序,每个字符串都应具有新行字符,并且以任何方式在第一个字符串的末尾匹配。我通过注释掉这两行来解决问题。

    //if(c=='\n')
    //   s[i++]=c;

这是更新的程序。

#include<stdio.h>
#define MAXLINE 1000

int mgetline(char line[],int maxline);
int any(char s1[],char s2[]);

int main(void)
{
    char s1[MAXLINE],s2[MAXLINE];
    int val;
    
    /* Give the first string s1 */
    
    mgetline(s1,MAXLINE);
    
    /* Give the second string s2 */

    mgetline(s2,MAXLINE);

    val = any(s1,s2);

    printf("%d",val);

    return 0;
}

int mgetline(char s[],int lim)
{
    int i,c;
    for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
        s[i]=c;

    //if(c=='\n')
    //   s[i++]=c;

    s[i]='\0';      
}

int any(char s1[],char s2[])
{
    int i, j, check_next_char;

    check_next_char = 1;

    for(i = 0; s1[i] != '\0' && (check_next_char);) 
    {
        // iterate through s2 while trying to find matching character from s1
        for(j = 0; s2[j] != '\0' && (s1[i] != s2[j]); ++j) 
            ; // continue

        if(s2[j] == '\0') {
            check_next_char=1;
            i++; // go for the next char in s1
        }
        else
            check_next_char=0; // match found
    }

    if(s1[i] == '\0')
        return -1;
    else
        return i;
}

推荐阅读