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

标签 c

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

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

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/

相关文章:

c - GTK3.0 GUI 在使用 "g_spawn_async_with_pipes()"时卡住

c - 尝试更改链表节点中的数据

c - 检测何时在 C 中连接了 USB 设备

无法在 c 的命令行参数中传递元素数组

c - glPopMatrix() 大喊 "unsupported texture format in setup_hardware_state"

C++ 宏 - for 循环中的错误

c - 链接器是否用于简单的 C 程序?

c - C中的进程循环

java - JFMI,标量变量的数量,传递字符串

c - 编译时出现警告,程序为 'waits/delays'