c - 为什么这个程序给变量 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,然后随着循环的进行一些随机数。我找不到代码的问题。这种行为的原因可能是什么?
解决方案
新行字符 '\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;
}
推荐阅读
- c# - Unity android 强制我的应用程序使用“全屏”按钮进入 16:9,而不是执行 18:9
- google-cloud-dataflow - 如何取消嵌套 Dataflow 中的嵌套 PCollection
- sonarqube - 如何将 sonarqube 构建断路器插件与 gitlab CI 集成?
- postgresql - Postgres:优化并发的同一行更新
- facebook - 如何在不中断 Facebook Graph API 调用的情况下获取数据?
- azure - Azure B2C 自定义策略授权端点给出 404
- javascript - 如何在 javascript 中发送 SOAP 请求,例如在 SoapUI 中
- php - 如何将数据从多维数组导出到 csv
- r - 如何删除箱线图上的刻度线
- spring-amqp - 消息已发布但从未到达代理