首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C中递归返回字符串值?

如何在C中递归返回字符串值?
EN

Stack Overflow用户
提问于 2018-08-27 11:08:19
回答 1查看 243关注 0票数 0

尝试在这里学到一些东西,而不是解决具体的问题。请帮助我找到一些在这种情况下适用的最佳实践,如果可能的话,请澄清一下原因。提前感谢您的帮助。

基本上,我是在已知范围内破解一个非常简单的哈希算法。函数根据散列测试字符串(在长度限制内)的可能性,直到它与传递的散列匹配。那么递归应该停止所有的迭代并返回匹配的字符串。迭代可以工作,但当找到答案时,似乎函数的每次运行都不会获得调用相同函数时返回的值。

以下是该函数的代码,为清楚起见,添加了额外的注释:

//'hash' is the hash to be replicated
//'leading' is for recursive iteration (1st call should have leading=="")
//'limit' is the maximum string length to be tested

string crack(string hash, string leading, int limit)
{
    string cracked=NULL, force=NULL, test=NULL;

    //as per definition of C's crypt function - validated
    char salt[3] = {hash[0], hash[1], '\0'};

    // iterate letters of the alphabet - validated
    for(char c='A'; c<='z'; c++)
    {
        // append c at the end of string 'leading' - validated
        test = append(leading,c);

        // apply hash function to tested string - validated
        force = crypt(test,salt);

        // if hash replicated, store answer in 'cracked' - validated
        if(strcmp(hash,force)==0)
        {
            cracked = test;
        }
        else
        {
            // if within length limit, iterate next character - validated
            if(strlen(test)<=limit+1)
            {
                // THIS IS WHERE THE PROBLEM OCCURS
                // value received when solution found
                // is always empty string ("", not NULL)
                // tried replacing this with strcpy, same result
                cracked = crack_des(hash,test,limit);
            }
        }

        // if answer found, break out of loop - validated
        if(cracked){break;}

        // test only alphabetic characters - validated
        if(c=='Z'){c='a' - 1;}
    }

    free(test);

    // return NULL if not cracked to continue iteration on level below
    // this has something to do with the problem
    return cracked;
} // end of function

根据我对指针的一点回忆,我猜它是通过传递引用而不是值来实现的,但我没有足够的知识来解决它。我已经阅读了this thread,但是这个建议似乎并没有解决这个问题--我尝试使用strcpy,也得到了同样的结果。

免责声明:这是哈佛大学在EDX举办的2018年CS50中的一项练习。这不会影响我的评分(我已经提交了这周的两个完美的练习,这是必须的),但如上所述,我正在寻找学习。

编辑:将标签编辑回C(正如评论中所阐明的,string来自string.h,append是我自己编写的,并多次验证--我稍后将使用TDD )。感谢您的评论;问题已解决,并从中吸取了教训!

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52032069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档