简体   繁体   English

用递归找到最长的单词C

[英]Find longest word C with recursion

I'm trying to find the size of the longest word in an array of structs. 我正在尝试在结构数组中查找最长单词的大小。 I have this array of structs: 我有这个结构数组:

struct Vocabolo{
    char parola[20];
    char *sinonimi[5];
    char definizione[300];
    };
typedef Vocabolo vocabolo;
vocabolo parole[30];

Now I have to use incremental recursion in order to find the size of the lognest word in the array. 现在,我必须使用增量递归来查找数组中最靠后的单词的大小。 Words are contained each in: 每个词包含在:

parole[n].parola

I'm using this code: 我正在使用此代码:

int Lunghezza_parola(vocabolo *parole,int n){
    int y;
    if(n == 1)
        return strlen(parole[0].parola);
    else {
        y = strlen(parole[n-1].parola);
        return Scegli_max(y,Lunghezza_parola(&parole,n-1));

    }
}

Wnere Scegli_max is: Wnere Scegli_max是:

int Scegli_max(int y, int lunghezzaStringa){
    if (y >= lunghezzaStringa)
        return y;
    else
        return lunghezzaStringa;
}

In this program the user has to insert words manually and each time a word is inserted, the program should put them in alphabetical order. 在此程序中,用户必须手动插入单词,并且每次插入单词时,该程序都应按字母顺序将它们放入。

If I try to input something like "come" as parole[0].parola and "hi" parole[1].parola and start this function the result is 3. Also it seems to works only if the longest word is in the last position of the array. 如果我尝试输入“ come”作为parole[0].parola和“ hi” parole[1].parola并启动此函数,则结果为3。似乎最长的单词位于最后一个单词时,它似乎也起作用数组的位置。

Any idea? 任何想法?

PS: this is part of a longer programm so is impossible to write here all the code but i'm quite sure everithing works fine exept this function so the words are ordered correctly in the array of struct. PS:这是较长程序的一部分,因此不可能在此处编写所有代码,但我敢肯定,此功能可以正常工作,因此单词在struct数组中的顺序正确。

Your problem is return Scegli_max(y,Lunghezza_parola(&parole,n-1)); 您的问题是return Scegli_max(y,Lunghezza_parola(&parole,n-1));

You call Lunghezza_parola giving it &parole which is already a vocabolo *parole so this becomes a vocabolo **parole and the pointer is now invalid. 您调用Lunghezza_parola,给它&parole,它已经是vocabolo *parole因此它变成了vocabolo **parole ,指针现在无效。

Try changing your return to return Scegli_max(y,Lunghezza_parola(parole,n-1)); 尝试更改您的退货以return Scegli_max(y,Lunghezza_parola(parole,n-1));

Your problem is the line return Scegli_max(y,Lunghezza_parola(&parole,n-1)); 您的问题是该行return Scegli_max(y,Lunghezza_parola(&parole,n-1)); . remove the & . 删除&

You should pass the value of the pointer, not a pointer to it. 您应该传递指针的值,而不是指向它的指针。

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

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