gpt4 book ai didi

c - 查找字符在字符串中的位置时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:43 25 4
gpt4 key购买 nike

我的函数返回了一个不正确的值。

我尝试在主函数中执行这段代码并且它有效

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com