在我的学校作业中,我必须找到一个带有蛮力算法的字符串。
例如,如果长度为 3,则这些是所有可能的组合: a b c aa ba ca ab bb cb ac bc cc aaa baa caa aba bba cba aca bca cca aab bab cab abb bbb cbb acb bcb ccb aac bac cac abc bbc cbc ACC 密件抄送 抄送
我在strcat.
这是代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define PASS_SIZE 3
char letters[] = "abc";
char test[] = "acb";
int count = 0;
int nbletters = sizeof(letters)-1;
int bruteForce(int size);
int main() {
    int i = 0;
    int notFound = 1;
    for (i = 1; i <= PASS_SIZE && notFound == 1; i++){
        notFound = bruteForce(i);
    };
    printf("Count: %d\n",count);
    return -1;
}
int bruteForce(int size){
    int i;
    int entry[size];
    char pass[50];
    char *temp;
    for(i=0 ; i<size ; i++){
        entry[i] = 0;
    }
    do {
        for(i=0 ; i<size ; i++){
            temp = letters[entry[i]];
            printf("%c", temp);
            strcat(pass,temp); /*Getting error here*/
       }
        count++;
        printf("\n");
        /*Compare pass with test*/
        if (strcmp (pass,test) == 0){
            return 0;
        };
       for(i=0 ; i<size && ++entry[i] == nbletters; i++){
            entry[i] = 0;
        }
    } while(i<size);
    return 1;
}
可能蛮力算法不是最好的算法。
为什么 strcat 不工作并且我得到分段错误?