c - 为什么这个 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;
}
}
解决方案
无论any()
返回什么都将在该行中被忽略:
any(str1, str2);
如果您需要在控制台上打印它,请使用printf()
:
printf("%d",any(str1, str2));
此外,s1[i] = '\0'
没有任何意义。您想处理直到\0
遇到 a ,所以s1[i] != '\0'
改为这样做。内循环也一样。
推荐阅读
- xstate - 如何从 xstate 中的状态获取所有可能的转换
- python-3.x - 将python输出复制到excel文件
- php - 如何在多个文件中调用@extends?
- ansible - 尝试动态生成数组 Jinja2
- python - 'DataFrame' 对象没有属性
- android - (Android Studio) 无法为 SD 卡上的文件创建 MediaPlayer
- c# - 设计模式建议 - 从 TXT 读取数据
- java - 在 docker 中使用 Java 执行本机应用程序(本机应用程序需要额外的本机库)
- python - 有没有办法将先前的值连续存储并在满足新条件时更改?
- c# - 如何复制内存
到 byte[] 中的特定偏移量