通过引用递归函数[关闭]

问题描述 投票:-2回答:2
#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:给定一个带空格的String,编写一个算法和一个C程序来计算它中的单词数和最长单词的长度。例如,如果输入字符串是“我喜欢编程”,那么单词的数量是3,最长字符串的长度是11。

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

c function recursion pass-by-reference
2个回答
1
投票

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

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

类似地,c++将指向c的地址提前一个,它不会增加c指向的整数(要做到这一点,你应该使用(*c)++)。


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


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;

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

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