通过引用递归函数

时间:2017-12-29 13:58:59

标签: c function recursion pass-by-reference

#include <stdio.h>

void word(char a[100], int i, int *max, int *c)
{
    printf("%d  %d", max , c);
    int length = 0;
    while (i < strlen(a) && a[i] != ' ')
    {
        length++;
        //printf("%c\n", a[i]);
        i++;
    }
    if (a[i] == ' ' && i < strlen(a))
    {
        c++;
        if (length > max)
            max = length;
        //printf("%d\n%d", max, c);    
        word(a, i + 1, max, c);
    }
}

void main()
{
    char a[100];
    int max = 0, j, i = 0, c = 0;
    scanf("%[^\n]s", &a);
    word(a, 0, &max, &c);
    printf("%d\n%d", c, max);
}

GIVEN PROBLEM 给定一个带空格的字符串,编写一个算法和一个C程序来计算其中的字数和最长字的长度。例如,如果输入字符串是'I love programming',那么单词的数量是3,最长字符串的长度是11。

我在递归函数max中通过引用传递变量cword()时遇到问题。变量未正确传递。我希望递归地通过引用传递变量,以便在每次递归调用时更新它们的值。我是stackoverflow的新手,所以无论我在哪里犯错,请纠正我。

2 个答案:

答案 0 :(得分:1)

使用*表示您传递的是指针,而不是引用(C没有引用)。您应该阅读一些信息页面,例如this really clear onethis,以熟悉两者之间的差异。

做例如。 max = length然后更改max指向的地址,而不是更改该地址的值。你的意思是*max = length,你取消引用指针以获取它指向的地址的值,然后分配给那个值,它会根据你的意愿更新“引用的”变量。鉴于此,printf("%d %d", max , c)不会打印值 - 您还需要更多*个。

同样,c++将指向c的地址提前一个,它不会增加c指向的整数(为此,您应该使用{{1} }})。

您应该始终至少使用(*c)++进行编译,因此编译器会为您提供完整的警告。在这种情况下,您将收到有关无效指针分配的多个警告,包括它们发生的位置,以便您可以更轻松地修复它们。

答案 1 :(得分:1)

我们初学者应该互相帮助。

你在这里。

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

size_t word( const char *s, size_t *max_word )
{
    size_t count = 0;

    s = s + strspn( s, " \t" );
    if ( *s )
    {
        ++count;

        size_t n = strcspn( s, " \t" );

        if ( *max_word < n ) *max_word = n;

        count += word( s + n, max_word );
    }

    return count;
}

int main(void) 
{
    const char *s = "I like programming using C";
    size_t max_word = 0;
    size_t n = word( s, &max_word );

    printf( "Number of words in the string is %zu\n"
            "The length of the maximum word is %zu\n ",
            n, max_word );

    return 0;
}

程序输出

Number of words in the string is 5
The length of the maximum word is 11

至于你的代码,那么对于根据C标准的初学者,没有参数的函数main应该被声明为

int main( void )

函数声明

void word(char a[100], int i, int *max, int *c);

太复杂了。如果你可以从函数返回一些有用的东西,你应该将它返回。

指定数组大小的第一个参数的声明没有多大意义,因为参数被调整为指针。

由于字符串未在函数中更改,因此应使用限定符const声明。

第二个参数是冗余的,因为包含字符串的字符数组的标记值等于'\0'。至少它应该有类型size_t

考虑到符号'\t'也可用作单词分隔符。

初始字符串和任何子字符串都可以以空格开头。但是你的功能忽略了这个事实。

第一个和第二个while循环可以永远执行,在这种情况下,该函数返回一个无效的字数和最大长度值。

此外这句话

c++;

没有意义,因为它增加了指针而不是增加指针指向的值。

本声明

max = length;

也会更改指针本身,而不是更改指针指向的值。

相关问题