简体   繁体   English

在C中返回一个指针,在字符串中查找值

[英]return a pointer in C, find value in string

I'm trying to learn C. I have a problem that asks me to loop through a string, find a value and return it. 我正在尝试学习C。我有一个问题,要求我循环遍历字符串,找到一个值并返回它。

int main(void)
{

    char *hello = "Hello";
    char *found_char = find_char(hello, 'e');
    printf("Found char: %s\n", found_char);
}

char *find_char(char *str, int c)
{
  int x;
  for (x = 0; str[x] != 0; x++){
    if (c == str[x]){
      return str[x];
    }
  }
}

and I get the following error 我得到以下错误

warning:returning 'char' from a function with return type 'char *' makes pointer from integer without a cast

I have a feeling I'm returning the wrong type, but I'm still a little fuzzy on how pointers work in C. Could anyone point out what I'm doing wrong, or what is going on this the pointer in the example problem? 我有一种返回错误类型的感觉,但是我对指针在C中的工作方式仍然有点模糊。有人可以指出我做错了什么,还是示例问题中指针在做什么? ?

str[x] is a char (specifically, it is an object of char type). str[x]是一个char (具体地说,它是char类型的对象)。

&str[x] is a pointer to char , also called a char * . &str[x]char的指针,也称为char *

Your function is declared to return char * . 您的函数被声明为返回char * So return a pointer to the char . 因此,返回一个指向char的指针。

you need to return a pointer to the string you found 您需要返回一个指向找到的字符串的指针

return str[x];

should be 应该

 return &(str[x]);

Note that you function is identical to the standard strchr function http://man7.org/linux/man-pages/man3/strchr.3.html 请注意,您的功能与标准strchr功能相同: http: strchr

Learn and understand from what the error is. 从错误中学习并了解。 It says that your returning a char but your function is defined to return pointer to a char(char )* 它说您返回一个char但您的函数已定义为返回指向char(char )*的指针

Instead of return str[x]; 而不是return str[x]; , return a pointer to a char using return &str[x]; ,使用return &str[x];返回指向char的指针return &str[x]; .

Also there's a workaround. 也有一种解决方法。

You can declare your function as 您可以将函数声明为

char find_char(){...}

instead of 代替

char *find_char(){...} . char *find_char(){...}

Also change your printf() statement. 同时更改您的printf()语句。

Here's the changes i made: 这是我所做的更改:

   int main(void)
  {

     char *hello = "Hello";
     char found_char = find_char(hello, 'e');
     printf("Found char: %s\n", found_char);
  }

  char find_char(char *str, int c)
 {
    int x;
    for (x = 0; str[x] != 0; x++){
    if (c == str[x]){
       return str[x];
    }
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM