我的函数返回了一个不正确的值。
我尝试在主函数中执行这段代码并且它有效
int f_char(char a[], char l)
{
int pos= 0;
for(int i=0; a[i]!='\0'; i++)
{
if(a[i]==l){
pos= i+1;
break;
}
}
return pos;
}
int main()
{
char a[256]= "Hola";
char l= 'l';
f_char(a, l);
printf("%c is in the position %d", l, f_char);
return 0;
}
预期的结果是:
l is in the 3 position
但它给了我:
l is in the 4199401 position
最佳答案
我认为函数没有问题。
#include<stdio.h>
int f_char(char a[], char l)
{
int pos= 0;
for(int i=0; a[i]!='\0'; i++)
{
if(a[i]==l){
pos= i+1;
break;
}
}
return pos;
}
int main(){
char *sen= "abcd";
char x = 'c';
printf("%d", f_char(sen, x));
return 0;
}
输出:3
关于c - 查找字符在字符串中的位置时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583013/