如何将此 C 算法从递归转换为迭代?

How can I convert this C algorithm from recursive to iterative?

当问题很聪明并且回答的人同样聪明时,你们都愚蠢到不喜欢

如何将此 C 函数从递归转换为迭代?我尝试使用 while 而不是 if then else 并在每次迭代时递增索引,但它不起作用。 iterazioneTutto 是一个递归函数,它在一个字符集上生成所有可能的字符串。不使用堆栈是可能的,但只有 while 循环?

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "attacchi.h"
#include "hash.h"

void iterazioneTutto(char *stringa, int index, int lunghezza);
char *checksum,*hashType;

void bruteforceConThread(char digest[],char tipohash[]) {
    int lunghezzaMinima,lunghezzaMassima, i;
    char *stringa = NULL;
    checksum = malloc(sizeof(char)*1024);
    hashType = malloc(sizeof(char)*1024);
    strcpy(checksum,digest);
    strcpy(hashType,tipohash);
    printf("Inserire la lunghezza minima da testare: ");
    scanf("%d", &lunghezzaMinima);
    printf("Inserire la lunghezza massima da testare: ");
    scanf("%d", &lunghezzaMassima);
    stringa = malloc(sizeof(char)*(lunghezzaMassima+1));
    memset(stringa, 0, lunghezzaMassima + 1);
    for (i = lunghezzaMinima; i <= lunghezzaMassima; i++) {
        iterazioneTutto(stringa, 0, i);
    }
}

void iterazioneTutto(char *stringa, int index, int lunghezza) {
    char c;
    if (index < (lunghezza - 1)) {
        for (c = ' '; c <= '~'; ++c) {
            stringa[index] = c;
            iterazioneTutto(stringa, index + 1, lunghezza);
        }
    } else {
        for (c = ' '; c <= '~'; ++c) {
            stringa[index] = c;
            stringa[index+1] = '\n';
            if(strcmp(hash(stringa,hashType),checksum)==0) {
                printf("Trovato!\nhash %s %s -> %s\n", checksum, hashType, stringa);
                exit(0);
            }
        }
    }
}

这是函数的迭代版本。我删除了 index 参数,因为它不再有任何用途:

void iterazioneTutto(char *stringa, int lunghezza) {
    int i;

    stringa[lunghezza] = '\n';
    for (i = 0; i < lunghezza; i++) {
        stringa[i] = ' ';
    }
    do {
        if(strcmp(hash(stringa,hashType),checksum)==0) {
            printf("Trovato!\nhash %s %s -> %s\n", checksum, hashType, stringa);
            exit(0);
        }
        i = lunghezza;
        while (i--) {
            if (stringa[i] < '~') {
                stringa[i]++;
                break;
            }
            stringa[i] = ' ';
        }
    } while (i >= 0);
}