-1

hello every one i was doing a C++ problem and found help on internet but one function confuse m that why we use pointer with function can any one explain me i am beginner in programming

char * replace_char( char *s, char source = 'a', char substitution = 'e' )
{
    if ( *s )
    {
        if ( *s == source ) *s = substitution;
        replace_char( s + 1, source, substitution );
    }

    return s;
}
4

2 回答 2

0

指针是一种数据类型,可以像任何其他数据类型(int、float、double...)一样从函数返回。在您的情况下,指向 char 的指针表示一个字符串,c 风格的字符串(与 char[] 基本相同)。函数返回指向数组第一个元素的指针(地址)

于 2019-10-28T07:50:00.743 回答
0

该函数将返回与变量输入“char* s”相同的字符指针。
函数可以返回指向数组开头的指针。

编辑:函数也可以这样写:

//This function will return an integer to indicate the number of replaced characters
int replace_char( char *sourcePtr, char source = 'a', char substitution = 'e' )
{
    int NrOfReplaced = 0;
    for(int i = 0; sourcePtr[i] != '\0'; i++)
    {
        if ( sourcePtr[i] == source )
        {
            sourcePtr[i] = substitution;
            NrOfReplaced++;
        }
    }
    return NrOfReplaced;
}
于 2019-10-28T07:51:34.220 回答