如何在返回字符*的函数中返回指针?

问题描述 投票:0回答:2

我正在实现自己的strrchr-它在由参数str指向的字符串中搜索字符c(无符号字符)的最后一次出现。

示例:

Input: f("abcabc" , "b")
Output: "bc"

函数应返回char *。我如何在函数中返回指向char数组的指针?

#include <stdio.h>
#include <string.h>    

char* my_strrchr(char* param_1, char param_2)
{
    int len = strlen(param_1);
    char res ;
    for(int i = len; i >= 0 ;i-- ){
        if (param_1[i] == param_2){
            res = param_1[i];
            return  *(res);
            //here i tried return (char) res, (char*) res; nothing works
        }
    }

    return NULL;
}

int main(){
    char *d = "abcabc";
    char r = 'b';
    my_strrchr(d, r);
    return 0 ;

}
pointers malloc c99
2个回答
1
投票

您正在尝试返回值,而不是指针。当*不是指针时,运算符res意味着通过指针获取值。您应该将其设置为指针然后返回:

char* my_strrchr(char* param_1, char param_2)
{
   int len = strlen(param_1);
   char *res ; //make it a pointer
   for(int i = len; i >= 0 ;i-- ){
       if (param_1[i] == param_2){
           res = &param_1[i]; //store address of an element to a pointer
           return  res; //return a pointer
       }
   }

   return NULL;
}

1
投票

您的变量res是char类型。要获取参考,请使用参考运算符&(请参见Meaning of "referencing" and "dereferencing" in C):

return &res

但是这将导致变量res的地址,而不是param_1数组中的地址。查看Alex的答案以获取正确的参考地址:https://stackoverflow.com/a/61930295/6669161

© www.soinside.com 2019 - 2024. All rights reserved.